SQL PL / SQL动态变量绑定

时间:2018-10-11 13:32:44

标签: sql oracle

我想在查询下面运行:

SELECT 
    * 
FROM 
    TABLE1
WHERE 
    COL1 = :DynamicValue1
    AND  COL2 = :DynamicValue2
USING 
    USERENTEREDVALUE1, USERENTEREDVALUE2;

我不想使用EXECUTE IMMEDIATE

如何在选择查询中使用using关键字? 当我运行它时,我会弹出来输入值,但它给出了错误 Ora-00933

2 个答案:

答案 0 :(得分:1)

您可以使用替换变量

DEFINE lname = 'Rogers'
DEFINE mgrid = 122

SELECT *
FROM employees
WHERE last_name = '&lname'
AND manager_id  = '&mgrid';

在SQL Developer或SQL * Plus中运行它时,您会得到

old:SELECT *
FROM employees
WHERE last_name = '&lname'
AND manager_id  = &mgrid
new:SELECT *
FROM employees
WHERE last_name = 'Rogers'
AND manager_id  = 122

EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DAT JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID
----------- -------------------- ------------------------- ------------------------- -------------------- -------- ---------- ---------- -------------- ---------- -------------
        134 Michael              Rogers                    MROGERS                   650.127.1834         26-08-06 ST_CLERK         2900                       122            50

或使用绑定变量

VARIABLE   lname VARCHAR2(40) 
VARIABLE  mgrid NUMBER 
EXEC :lname := 'Rogers'
EXEC :mgrid := 122
VARIABLE x REFCURSOR


BEGIN
     OPEN :x FOR SELECT *
                 FROM employees
                 WHERE last_name =:lname 
                 AND manager_id =:mgrid;
END;
/

    PRINT x

结果

PL/SQL procedure successfully completed.


PL/SQL procedure successfully completed.


PL/SQL procedure successfully completed.



EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DAT JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID
----------- -------------------- ------------------------- ------------------------- -------------------- -------- ---------- ---------- -------------- ---------- -------------
        134 Michael              Rogers                    MROGERS                   650.127.1834         26-08-06 ST_CLERK         2900                       122            50

答案 1 :(得分:0)

我不确定您是否正在执行pl/sql,但是如果您这样做,则可以简单地向查询中添加变量:

declare
    USERENTEREDVALUE1 VARCHAR2(100) := 'value1';
    USERENTEREDVALUE2 VARCHAR2(100) := 'value2';
    RESULTVALUE VARCHAR2(100);
begin

    SELECT COL3
      INTO RESULTVALUE
      FROM  (
                SELECT 'value1' COL1, 'value2' COL2, 'Ok' COL3 FROM dual UNION ALL
                SELECT 'value3' COL1, 'value4' COL2, 'NOK' COL3 FROM dual
            ) TABLE1
    WHERE COL1 = USERENTEREDVALUE1
      AND COL2 = USERENTEREDVALUE2;

    dbms_output.put_line('RESULTVALUE: ' || RESULTVALUE); 
end;