PL/SQL动态SQL
我想根据传入的值是否为空来拼接条件查询语句,但是字符串拼出来了,执行有问题。
--1.创建包,定义游标
create or replace package curspack as
type refcurs is ref cursor;
end;
--2.条件查询的存储过程
create or replace procedure sp_condition_search
(
v_id t_user.id%type,
v_name t_user.username%type,
v_password t_user.password%type,
v_refcurs out curspack.refcurs
)
is
v_sql varchar2(500);
begin
v_sql := 'select * into v_refcurs from t_user where 1=1';
if(v_id is not null or nvl(v_id,'null') <> 'null')
then v_sql := v_sql || ' and id='||v_id;
end if;
if(v_name is not null or nvl(v_name,'null') <> 'null')
then v_sql := v_sql || ' and username='||v_name;
end if;
if(v_password is not null or nvl(v_password,'null') <> 'null')
then v_sql := v_sql || ' and password='||v_password;
end if;
dbms_output.put_line(v_sql);
open v_refcurs for v_sql;--这句出错
end;
--3.调用
declare
v_refcurs curspack.refcurs;
begin
sp_condition_search(1,null,null,v_refcurs);
end;
错误信息:
ORA-00905: 缺失关键字
ORA-06512: 在 "TEST.SP_CONDITION_SEARCH", line 22
ORA-06512: 在 line 5
------解决方案--------------------
既然是生成CURSOR,就不能用INTO,改成:
v_sql := 'select * from t_user where 1=1';