MySQL properly use of if exists

80 Views Asked by At

I'm making a procedure that retrieves a client information, the thing is that there are two types of client with different attributes, so I need a different return for the query depending on the client type joining it with a parent table... I made this but apparently i'm making some syntax mistakes:

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

There are 2 best solutions below

0
On BEST ANSWER

You didn't terminate your first begin.

It's easier to see the error if you indent your code consistently:

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; 
&

You need a final end at the same level of indentation as the first begin.

2
On

i have fixed it!

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
&

thank you guys!