pl/sql - Using a dynamic query inside a stored procedure

后端 未结 3 1492
傲寒
傲寒 2020-12-18 11:31

I am using a stored procedure to insert data into a temp table using a cursor. This procedure stores a dynamic query inside a variable to mount the insert/update command.

3条回答
  •  無奈伤痛
    2020-12-18 12:25

    Don't build your query by appending strings. You leave yourself open to lots of bugs and vulnerabilities, first of all SQL injection. The need to use dynamic queries doesn't justify not using bind variables. If you really need to use dynamic queries (it is not clear from your example why static update wouldn't work?!), do this instead:

    FOR vc2 IN (...) LOOP
       v_sql := 
           'BEGIN
                V_UPD NUMBER := 0;
    
                SELECT (SELECT ID_TIPO_TERR  
                  FROM ZREPORTYTD_TMP 
                 WHERE AUDITORIA = :p1
                   AND TERRITORIO = :p2
                   AND PRODUTO = :p3) 
                  INTO V_UPD FROM DUAL;
    
                UPDATE ZReportYTD_TMP
                   SET TARGET = :p4
                 WHERE AUDITORIA = :p5
                   AND TERRITORIO = :p6
                   AND PRODUTO = :p7;
            END';
       EXECUTE IMMEDIATE v_sql USING VC2.AUDITORIA, VC2.NOME, VC2.PRODUTO, 
                                     VC2.OBJETIVO, VC2.AUDITORIA, VC2.NOME, 
                                     VC2.PRODUTO;
    END LOOP;
    

    Oracle will correctly bind with the appropriate type.

提交回复
热议问题