Instead of writing out a long description here's an example:
DECLARE v_sql VARCHAR2 (255); v_result VARCHAR2 (255); BEGIN v_sql := 'select ''hello'' into :a from dual'; EXECUTE IMMEDIATE v_sql INTO v_result; DBMS_OUTPUT.put_line (v_result); END;
Notice how I had to put 2 single quotes around "Hello" to escape the single quote characters?
Now using the q function I don't need to do that:
DECLARE v_sql VARCHAR2 (255); v_result varchar2(255); BEGIN v_sql := q'!select 'hello' into :a from dual !'; EXECUTE IMMEDIATE v_sql INTO v_result; DBMS_OUTPUT.put_line (v_result); END;
Notice now how "Hello" is wrapped as it would appear if it were not in variable definition function?
This can save you a lot of time by avoiding having to escape single quotes in strings!
Update: q Function Inside a q Function
This was very helpful. Thanks!
ReplyDeleteThank you, Martin.
ReplyDeleteI found that this technique works for report-specific custom column attributes as in this example:
DECLARE
v_sql VARCHAR2(3000);
v_result VARCHAR2(3000);
BEGIN
v_sql := q'!select 'Crew
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -12), 'Mon yyyy')||'
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -11), 'Mon yyyy')||'
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -10), 'Mon yyyy')||'
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -9), 'Mon yyyy')||'
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -8), 'Mon yyyy')||'
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -7), 'Mon yyyy')||'
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -6), 'Mon yyyy')||'
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -5), 'Mon yyyy')||'
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -4), 'Mon yyyy')||'
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -3), 'Mon yyyy')||'
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -2), 'Mon yyyy')||'
:Total WOs Due '||to_char(ADD_MONTHS(TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'),'YYYY-MM'), -1), 'Mon yyyy')
from dual!';
EXECUTE IMMEDIATE v_sql INTO v_result;
RETURN v_result;
END;
Hi Scott,
DeleteGlad that it helped out. On a side note you could modify your query to the following to make it easier for maintenance:
SELECT to_char(ADD_MONTHS(SYSDATE, -level + 1), 'Mon YYYY')
FROM dual
connect by level <= 12;
Hope this helps,
Martin
I think you were a victim of plagiarism - > http://oracleapexsolutions.blogspot.co.uk/2012/08/q-function-in-apex-escape-single-quotes.html
ReplyDeleteThanks for the heads up. Don't think there is much I can do...
Delete