Oracle
使用綁定變數時如何解決錯誤“ORA:01-006:綁定變數不存在”?
我有一個具有以下結構和數據的表:
create table TEST_TABLE ( item_number NUMBER, item_name VARCHAR2(50), item_col VARCHAR2(50), item_pol VARCHAR2(50) )
樣本數據:
item_number | item_name| item_col | item_pol ------------------------------------------------ 1 | blue | b | c 2 | red | d | a 3 | black | e | a 4 | yellow | d | b
這是我嘗試使用的範常式序
bind variables
。create or replace procedure test_bind_variable(res out sys_refcursor, item_number varchar2, item_name varchar2, item_col varchar2, item_pol varchar2) is qry varchar2(8000); begin qry := 'select * from test_table where 1=1 '; if (item_number is not null) then qry := qry || ' and item_number = :1 '; end if; if (item_name is not null) then qry := qry || ' and item_name = :2 '; end if; if (item_col is not null) then qry := qry || ' and item_col= :3 '; end if; if (item_pol is not null) then qry := qry || ' and item_pol = :4 '; end if; dbms_output.put_line(qry); open res for qry using item_number, item_name, item_col, item_pol; end;
問題是當所有輸入參數都有值時,程序正常工作,沒有任何錯誤,但是當只有一個或兩個參數有值時,我收到這個錯誤:
ORA-01006: bind variable does not exist,
。我怎麼解決這個問題?有些參數可能有值,有些可能沒有。提前致謝
您可以完全避免使用動態 SQL(您也不應該將 PL/SQL 變數命名為與表列相同的名稱):
create or replace procedure test_bind_variable(res out sys_refcursor, p_item_number varchar2, p_item_name varchar2, p_item_col varchar2, p_item_pol varchar2) is qry varchar2(8000); begin open res for select * from test_table where (p_item_number is null or p_item_number = item_number) and (p_item_name is null or p_item_name = item_name) and (p_item_col is null or p_item_col = item_col) and (p_item_pol is null or p_item_pol = item_pol) end;
PS。與我不同,確保您考慮運算符的優先級。