I am creating a query like this:
v_sql:=' SELECT abc FROM '||v_table||'
WHERE area IN ('''||v_area||''')
AND (
('''||p_supp_nbr||''' IS NULL)
OR
supplr_vn IN ('''||p_supp_nbr||''')
)
Now when the p_supp_nbr is NULL then its not taking.
I get like this:
((''IS NULL) OR (supplr_vn =''))
Its checking space in the table
but i want ((NULL IS NULL) OR (supplr_vn =NULL)) so that condition bcomes ineffective
3 Answers 3
Don't do that! You risk SQL Injection issues. Use bind variables:
v_sql:= 'SELECT abc FROM '||v_table||
' WHERE area = :v_area
AND (
:p_supp_nbr IS NULL
OR
supplr_vn = :p_supp_nbr
)
Of course since you know at the point of generating the dynamic SQL whether the value is null you could instead do this:
v_sql:= 'SELECT abc FROM '||v_table||'
WHERE area = :v_area';
IF p_supp_nbr IS NULL THEN
v_sql := v_sql || ' AND :p_supp_nbr IS NULL';
ELSE
v_sql := v_sql || ' AND supplr_vn = :p_supp_nbr';
END IF;
Either way you can then bind the values at runtime like this:
OPEN my_refcursor FOR v_sql USING v_area, p_supp_nbr;
2 Comments
if statement superfluous? Wouldn't this work: IF p_supp_nbr IS NOT NULL THEN v_sql := v_sql || ' AND supplr_vn = :p_supp_nbr'; END IF;Try this:
v_sql:=' SELECT abc FROM '||v_table||'
WHERE area IN ('''||v_area||''')
AND (('''||p_supp_nbr||''' IS NULL)
OR supplr_vn IN ('''||NVL(p_supp_nbr, 'NULL')||'''))
1 Comment
General Oracle example:
DECLARE
v_sql1 VARCHAR2(200);
v_sql2 VARCHAR2(200);
v_tab_name VARCHAR2(200):= 'scott.emp';
v_listCol VARCHAR2(200):= 'job';
v_list VARCHAR2(200):= '''MANAGER'', ''CLERK''';
--
v_colName VARCHAR2(200):= 'comm';
v_comm NUMBER:= 1400;
BEGIN
v_sql1:= 'SELECT * FROM '|| v_tab_name ||' WHERE '||v_listCol ||' IN (:v)';
v_sql2:= 'SELECT * FROM '|| v_tab_name ||' WHERE ('||v_colName ||' = :v OR '||v_colName ||' IS NULL)';
--
EXECUTE IMMEDIATE v_sql1 USING v_list;
dbms_output.put_line(v_sql1);
--
EXECUTE IMMEDIATE v_sql2 USING v_comm;
dbms_output.put_line(v_sql2);
END;
/
Comments
Explore related questions
See similar questions with these tags.
null is null.null is nullas a part of anywhereclause. Simply don't include that part of thewhereclause ifp_supp_nbr is null.null. Null isn't a value. Just alter thewhereclause depending on which (if any) of your parameters happen to benull.