elk 执行动态查询语句有两种方式:
方式一:使用 execute immediate select sql语句
方式二:使用游标 open for
方式一:select 语句写在单引号中,into/using 不需要写在单引号中
语法:
execute immediate 'select 字段名1,字段名2 。。。 where 字段名1 = :1 ,字段名2 = :2 。。。' into 接收字段1,接收字段2 using in 替换占位符1, 替换占位符2; execute immediate 'select 字段名1,字段名2 。。。 where 字段名1 = :1 ,字段名2 = :2 。。。' using in 替换占位符1, 替换占位符2。。。,out 输出接收字段名1,输出接收字段名2。。。;
|
--根据传进来的name值,把查询出的eno输出 declare name_i varchar(23); --输入参数 name_o int; --输出接收参数 begin -- :1 代表占位,执行时会被using后定义的参数值替换,using后 in 参数名代表入参,out 参数名代表出参; execute immediate 'select eno from emp where ename = :1' into name_o using in name_i ; end; / |
declare name_i varchar(23); --输入参数 name_o int; --接收输出参数 begin --使用out时不能有into execute immediate 'select eno from emp where ename = :1 ' using in name_i, out name_i ; end; / |
方法二:open for
declare type cursor_type is ref cursor; --定义数据类型,类型为游标 cursor_name cursou_type; --定义变量,变量类型为自定义的游标类型
sql_str varchar2(212); --定义SQL查询语句字符串变量 ename_i varchar2(23) := '张三'; --定义输入参数 eno_o varchar2(23) ; --接收输出参数
begin sql_str = 'select eno from emp where ename = :1'; open cursor_name for sql_str using in ename_i -- 打开游标
fetch cursor_name into eno_o; -- 从游标中获取数据
while cursor_name%found loop dbms_output.put_line(eno_o); fetch cursor_name into eno_o; -- 从游标获取下一条数据 end loop;
close cursor_name; ---关闭游标
end; / |