MySQL正确使用if存在

时间:2014-11-18 04:49:32

标签: mysql if-statement syntax syntax-error exists

我正在创建一个检索客户端信息的过程,那就是有两种类型的客户端具有不同的属性,所以我需要一个不同的查询返回值,具体取决于将其与父项连接的客户端类型table ...我做了这个,但显然我犯了一些语法错误:

delimiter &
create procedure show_Client(in id varchar(10)) 
begin 
if (exists (select ID from CLIENT_1 as C1 where id =C.ID),1,0) 
then 
begin 
select * from CLIENT_1 as C1 join CLIENT C on C1.ID=C.ID where C1.ID=id; 
end; 
else 
BEGIN 
select * from CLIENT_2 as C2 join CLIENT C on C2.ID=C.ID where C2.ID=id; 
end; 
end if; 
&

2 个答案:

答案 0 :(得分:0)

您没有终止第一个begin

如果一致地缩进代码,则更容易看到错误:

delimiter &

create procedure show_Client(in id varchar(10)) 
begin 
    if (exists (select ID from CLIENT_1 as C1 where id =C.ID),1,0) 
    then 
        begin 
            select * from CLIENT_1 as C1 join CLIENT C on C1.ID=C.ID where C1.ID=id; 
        end; 
    else 
        begin 
            select * from CLIENT_2 as C2 join CLIENT C on C2.ID=C.ID where C2.ID=id; 
        end; 
    end if; 
&

您需要与第一个end相同的缩进级别begin

答案 1 :(得分:0)

我修好了!

delimiter &
create procedure show_Client(in id varchar(10)) 
begin 
    if (select exists (select C1.ID from CLIENT_1 as C1 where id=C1.ID)=true) 
    then 
        begin 
            select * from CLIENT_1 as C1 join PARENT_CLIENT as CP on C1.ID=CP.ID where C1.ID=id; 
        end; 
    else 
        begin 
            select * from CLIENT_2 as C2 join PARENT_CLIENT as CP on C2.ID=CP.ID where C2.ID=id; 
        end; 
    end if; 
end
&
谢谢你们!