我必须部署我的sql脚本,为此我在一个文件中定义了变量,在另一个文件中创建了脚本。
文件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查询中替换字符串变量。
答案 0 :(得分:1)
或者,您可以在SQL字符串中使用该变量,只需记住添加引号 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 :(得分: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;