2015-09-20 54 views
0

要求是通過用單引號作爲參數變量執行Immediate.I迄今嘗試下面的代碼片段..消化替代變量撇號

如何讓下面的工作代碼?

declare 
v_val varchar2(5); 
v_match varchar2(5); 
v_query VARCHAR2(500); 
begin 
v_val:='a''a'; 
    dbms_output.put_line(v_val); 
v_val:=replace(v_val,'''',''''''); 
    dbms_output.put_line(v_val); 
    v_query:='select val from test where val='||''''||v_val||''''||' and 1=1';      
    execute immediate v_query into v_match; 
    if(v_match=v_val) then 
    dbms_output.put_line('match found'); 
    else 
    dbms_output.put_line(' no match found'); 
end if; 
    end; 

換句話說: 我想接受撇號輸入到替代變量,然後使用該變量SELECT語句的where子句中,從表中提取數據。

我的p值:a'a select * from tabl where keyval =&inputval;

+1

你爲什麼不使用綁定變量? – Husqvik

+0

REPLACE調用v_val應該有'a''a'後,但是你的SELECT語句正在尋找v_val中不存在的前導和尾隨的撇號。也許這會給你一個想法。祝你好運。 –

+0

可能重複[PL/SQL,如何在字符串中單引號轉義?](http://stackoverflow.com/questions/11315340/pl-sql-how-to-escape-single-quote-in-a-串) – Ollie

回答

1

使用綁定變量:

declare 
    v_val varchar2(5); 
    v_match varchar2(5); 
    v_query VARCHAR2(500); 
begin 
    v_val:='aa'; 
    dbms_output.put_line(v_val); 
    v_val:=replace(v_val,'''',''''''); 
    dbms_output.put_line(v_val); 
    v_query:='select val from test where val=:val and 1=1';      
    execute immediate v_query into v_match using v_val; 
    dbms_output.put_line('match found'); 
EXCEPTION 
    WHEN NO_DATA_FOUND THEN 
    dbms_output.put_line(' no match found'); 
end; 
/

或不使用動態SQL:

declare 
    v_val TEST.VAL%TYPE; 
    v_match TEST.VAL%TYPE; 
begin 
    v_val:='a''a'; 
    dbms_output.put_line(v_val); 
    v_val:=replace(v_val,'''',''''''); 
    dbms_output.put_line(v_val); 
    select val INTO v_match from test where val=v_val; 
    dbms_output.put_line('match found'); 
EXCEPTION 
    WHEN NO_DATA_FOUND THEN 
    dbms_output.put_line(' no match found'); 
end; 
/