适当使用绑定变量
Appropriate Use of Bind Variables
在下面的PL/SQL块中,WHERE子句中使用了一个绑定变量:
declare
symbol varchar2(6) := 'EPIC';
begin
execute immediate 'delete from stock where symbol = :symbol'
using symbol;
end;
/
此块执行成功,但是,类似以下的内容将失败:
declare
symbol varchar2(15) := 'employees';
begin
execute immediate 'delete from :symbol where last_name = ''Kochar'''
using symbol
end;
/
我的问题是:除了像第一个示例那样将值传递给 WHERE 子句之外,我们能否在任何其他上下文中使用绑定变量?
绑定变量只是传输值。
它允许重复使用相同的查询,但具有不同的值。
一个 table 名称不是一个值。
You can bind into your SQL statement only those expressions(literals,
variables, complex expressions) that replace placeholders for data
values inside the dynamic string. you cannot bind in the names of
schema elements(tables, columns, etc) or entrie chunks of the SQL
statement. For those parts of your string, you must use
concatenation(operator)
所以使用如下:
SQL> create table employees(empid int,last_name varchar2(50));
Table created
SQL> insert into employees values(111,'Kochar');
1 row inserted
SQL> select * from employees;
EMPID LAST_NAME
----- ----------
111 Kochar
SQL>
SQL> declare
2 symbol varchar2(15) := 'employees';
3 begin
4 execute immediate 'delete '||symbol||' where last_name = ''Kochar''';
5 end;
6 /
PL/SQL procedure successfully completed
SQL> select * from employees;
EMPID LAST_NAME
----- ----------
-- i.e. no row(s) returned.
在下面的PL/SQL块中,WHERE子句中使用了一个绑定变量:
declare
symbol varchar2(6) := 'EPIC';
begin
execute immediate 'delete from stock where symbol = :symbol'
using symbol;
end;
/
此块执行成功,但是,类似以下的内容将失败:
declare
symbol varchar2(15) := 'employees';
begin
execute immediate 'delete from :symbol where last_name = ''Kochar'''
using symbol
end;
/
我的问题是:除了像第一个示例那样将值传递给 WHERE 子句之外,我们能否在任何其他上下文中使用绑定变量?
绑定变量只是传输值。
它允许重复使用相同的查询,但具有不同的值。
一个 table 名称不是一个值。
You can bind into your SQL statement only those expressions(literals, variables, complex expressions) that replace placeholders for data values inside the dynamic string. you cannot bind in the names of schema elements(tables, columns, etc) or entrie chunks of the SQL statement. For those parts of your string, you must use concatenation(operator)
所以使用如下:
SQL> create table employees(empid int,last_name varchar2(50));
Table created
SQL> insert into employees values(111,'Kochar');
1 row inserted
SQL> select * from employees;
EMPID LAST_NAME
----- ----------
111 Kochar
SQL>
SQL> declare
2 symbol varchar2(15) := 'employees';
3 begin
4 execute immediate 'delete '||symbol||' where last_name = ''Kochar''';
5 end;
6 /
PL/SQL procedure successfully completed
SQL> select * from employees;
EMPID LAST_NAME
----- ----------
-- i.e. no row(s) returned.