Link to home
Start Free TrialLog in
Avatar of renesisx
renesisx

asked on

How to use CASE and EXISTS?

PostgreSQL question...

I want something like this:
CASE WHEN EXISTS(SELECT constraint_name FROM information_schema.table_constraints WHERE constraint_name = 'FK_ProductPurchased_Customer') THEN
ALTER TABLE "ProductPurchased" DROP CONSTRAINT "FK_ProductPurchased_Customer"
END;

But that's not valid SQL.

Do you know a way to do that with valid PostgreSQL SQL?
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

In SQL you cannot use CASE as a decicion loop, such as...

IF (some criteria) THEN
   'do this
else
   'do that
end if

Instead, use the SQL IF construct (no THEN or END IF required, but good to surround commands with begin..end)
IF EXISTS(SELECT constraint_name FROM information_schema.table_constraints WHERE constraint_name = 'FK_ProductPurchased_Customer')    
   begin
   ALTER TABLE "ProductPurchased" DROP CONSTRAINT "FK_ProductPurchased_Customer"
   end

..or..

SELECT @some_variable = constraint_name FROM information_schema.table_constraints WHERE constraint_name = 'FK_ProductPurchased_Customer')  

IF @some_variable IS NOT NULL
   begin
   'do your stuff here
   end
Avatar of renesisx
renesisx

ASKER

Can you do that in PostgreSQL though? As I understood it, it doesn't have an IF statement?
ASKER CERTIFIED SOLUTION
Avatar of dominik-jesiolowski
dominik-jesiolowski

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
My comment was for SQL Server; I didn't read the PostgreSQL requirement of your question.  Please disregard my earlier comments.
Thank you Dominik! I wouldn't have figured that one out on my own - it was harder than I imagined.
Imhorn: No problem, thanks for trying :)