-
Notifications
You must be signed in to change notification settings - Fork 18
/
replacef.sql
82 lines (72 loc) · 2.83 KB
/
replacef.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
-- --------------------------------------------------------------------------------------
--
-- Script: replacef.sql
--
-- Version: 1.1
--
-- Author: Adrian Billington
-- www.oracle-developer.net
--
-- Description: A function and collection type to simplify building and debugging of
-- strings, particularly dynamic SQL.
--
-- Example Usage
-- -------------
--
-- a) Debugging based on inputs
--
-- DECLARE
-- v_sql VARCHAR2(128);
-- nt_args replacef_ntt := replacef_ntt();
-- BEGIN
-- v_sql := 'ALTER TABLE %s.%s TRUNCATE PARTITION %s';
-- nt_args := replacef_ntt('table_owner','table_name','partition_name');
-- DBMS_OUTPUT.PUT_LINE(replacef(v_sql,nt_args));
-- END;
-- /
--
-- b) Building strings for execute
--
-- DECLARE
-- v_sql VARCHAR2(128);
-- nt_args replacef_ntt := replacef_ntt();
-- BEGIN
-- v_sql := 'ALTER TABLE %s.%s TRUNCATE PARTITION %s';
-- nt_args := replacef_ntt('table_owner','table_name','partition_name');
-- v_sql := replacef(v_sql,nt_args);
-- EXECUTE IMMEDIATE v_sql;
-- END;
-- /
--
-- Note that the number of replacements is determined by whichever has the
-- fewest components - that is, the least of the number of placeholders in
-- the string or the number of elements in the collection. You might wish
-- to change this to raise an exception on mismatch.
--
-- History: 1.0: initial version
-- 1.1: bug-fix in v_args algorithm (thanks to Jason Weinstein for correction)
--
--
-- --------------------------------------------------------------------------------------
CREATE TYPE replacef_ntt AS TABLE OF VARCHAR2(4000);
/
CREATE FUNCTION replacef ( p_msg IN VARCHAR2,
p_args IN replacef_ntt DEFAULT replacef_ntt(),
p_plc IN VARCHAR2 DEFAULT '%s' ) RETURN VARCHAR2 IS
v_msg VARCHAR2(32767) := p_msg;
v_args PLS_INTEGER := LEAST((LENGTH(v_msg)-LENGTH(REPLACE(v_msg,p_plc)))/LENGTH(p_plc),p_args.COUNT);
v_pos PLS_INTEGER;
BEGIN
FOR i IN 1 .. v_args LOOP
v_pos := INSTR( v_msg, p_plc );
v_msg := REPLACE(
SUBSTR( v_msg, 1, v_pos + LENGTH(p_plc)-1 ), p_plc, p_args(i)
) || SUBSTR( v_msg, v_pos + LENGTH(p_plc) );
END LOOP;
RETURN v_msg;
END replacef;
/
CREATE PUBLIC SYNONYM replacef_ntt FOR args_ntt;
CREATE PUBLIC SYNONYM replacef FOR replacef;
GRANT EXECUTE ON replacef_ntt TO PUBLIC;
GRANT EXECUTE ON replacef TO PUBLIC;