如何将字符串变量传递给动态 sql 中的 where 子句
how to pass a string variable to the where clause in dynamic sql
我必须部署我的 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';
这只是我的大脚本的一个示例,但 objective 是如何在动态 sql.
的 where 查询中替换字符串变量
最好是用户绑定变量和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;
或者,你可以使用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;
我必须部署我的 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';
这只是我的大脚本的一个示例,但 objective 是如何在动态 sql.
的 where 查询中替换字符串变量最好是用户绑定变量和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;
或者,你可以使用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;