Oracle(存储过程,触发器等中) if语句中不能有子查询的原因和解决方案

来源:互联网 发布:linux write 编辑:程序博客网 时间:2024/06/06 03:56

如果我们输入并运行以下代码:

 

begin  if 'U001' in (select userId from userInfo)    then dbms_output.put_line('用户编号重复');  end if;end;

 

会得到以下的错误信息:

可以知道,PL/SQL中,if语句是不能有子查询的,PL/SQL的语法有限制。IF 后面只能是逻辑表达式

 

 

实际应用中

如创建以下存储过程

create or replace procedure proc_user_reg(Param_userId varchar2,Param_realName varchar2,Param_password varchar2)isbegin  if Param_userId in (select userId from userInfo)   then dbms_output.put_line('用户编号重复');    else      insert into userInfo values(Param_userId,Param_realName,Param_password,default);   end if;end;在调用此存储过程中也会出现上面的问题

 

 


解决方法:
定义一个变量,通过count(*)来统计原表中重复数据的个数。相当于用另一种方法实现了IN语句的判断

--变量的定义声明在is或as后

create or replace procedure proc_user_reg(Param_userId varchar2,Param_realName varchar2,Param_password varchar2)is countResult number;begin  select count(*) into countResult from userInfo where userId=Param_userId;  if countResult=0   then insert into userInfo values(Param_userId,Param_realName,Param_password,default);    else       dbms_output.put_line('用户编号重复');  end if;end;