2016-09-08 11 views
0

私はSQLスクリプトをデプロイしなければならず、そのために1つのファイルに変数を定義し、別のファイルにスクリプトを作成しています。動的SQLのwhere句に文字列変数を渡す方法

ファイル1:

Define_Variable.sql

DEFINE hr_SCHEMA = hr; 

ファイル2:

Createfile.sql

@Define_variable.sql 

declare 
v_str varchar2(3000); 
lc_cnt number; 
BEGIN 
    v_str :='select count(1) into l_cnt from dba_tab_cols where owner=''' || &hr_SCHEMA ||''' and TABLE_NAME=''employees'''; 
    execute immediate v_str; 
    IF l_cnt = 0 then 

    -----perform some operations 
    end if; 
end ; 
/

私は次のエラーを取得しています。 ORA-06550およびPLS-00201: identifier 'hr' must be declared。 ここでは値が代入されていますが、値を引用符で囲みます。私の出力が

select count(1) into l_cnt from dba_tab_cols where owner= 'hr' and TABLE_NAME='employees'; 

を実行しなければならないと同じようにこれはちょうど私の大きなスクリプトの例ですが、目的は、動的SQLのwhereクエリで文字列varibleをsubstitureする方法です。

答えて

0

ユーザーバインド変数とusing句に最適です。

declare 
    v_str varchar2(3000); 
    lc_cnt number; 
begin 
    v_str := 'select count(1) from dba_tab_cols where owner=:owner and TABLE_NAME=''employees'''; 
    execute immediate v_str into l_cnt using '&HR_schema'; 
    if l_cnt = 0 
    then 
     -----perform some operations 
    end if; 
end; 
+0

おかげトンを追加することを忘れないでください、SQL文字列内の変数を使用することができます。 –

1

はまた、あなただけの、それはルネ今取り組んでいる引用符where owner= ''&HR_schema''

set serveroutput on 
define HR_schema = hr 

    declare 
     v_str varchar2(3000); 
     l_cnt number; 
    begin 
     --v_str := 'select count(1) from dba_tab_cols where owner=:owner and TABLE_NAME=''employees'''; 
     v_str := 'select count(1) from dba_tab_cols where owner= ''&HR_schema'' and TABLE_NAME=''employees'''; 
     execute immediate v_str into l_cnt ; --using '&HR_schema'; 
     if l_cnt = 0 
     then 
     dbms_output.put_line(l_cnt); 
      -----perform some operations 
     end if; 
    end; 
+1

https://blogs.oracle.com/sql/entry/improve_sql_query_performance_by – Rene

+0

ここでのパフォーマンスの向上は非常に小さいかもしれません。なぜなら、バインド変数の解決策は、SQLの実行が困難なハード解析ここのケース。一方、ヒストグラムを利用する場合は、バインド変数を使用するとパフォーマンスに影響を与える可能性があります。最初の解析では、変数の非極性値を持つ可能性がありますが、CBOはインデックスを使用することを選択しますが、成功した実行には一般的な値が付く可能性があります。この場合、いくつかのハード・パースは、最適ではないプランを使用してSQLを実行するよりも優れたソリューションになる可能性があります。 –

+0

@Rene - バインドの問題は、多くの異なるスキーマに対して何度も実行されるまで重要になりません。 –

関連する問題