Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use AND condition in IF EXISTS in SQL?

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'X' AND COLUMN_NAME = 'Y')   IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Z' AND COLUMN_NAME = 'A') BEGIN     UPDATE [dbo].[X]          SET Y= (SELECT inst.[A] FROM [dbo].[Z] s WHERE s.[B] = [dbo].[x].[B]); END         GO 

I want to combine the 2 IF confitions and perform the update only when both of them are satisfied. Is there some way in which I can club 2 IF EXISTS?

like image 651
user811433 Avatar asked Jul 01 '13 23:07

user811433


People also ask

What is in and EXISTS in SQL?

Key differences between IN and EXISTS OperatorThe IN clause scan all records fetched from the given subquery column, whereas EXISTS clause evaluates true or false, and the SQL engine quits the scanning process as soon as it found a match.

Can I use if EXISTS in SQL?

It works fine if the object exists in the database. In case the object does not exist, and you try to drop, you get the following error. To avoid this situation, usually, developers add T-SQL If Exists statement and drop the object if it is already available in the database.

WHERE clause if EXISTS SQL?

Using EXISTS clause in the CASE statement to check the existence of a record. Using EXISTS clause in the WHERE clause to check the existence of a record. EXISTS clause having subquery joining multiple tables to check the record existence in multiple tables.

How do you check if record already exist in SQL?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.


1 Answers

Simple:

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'X' AND COLUMN_NAME = 'Y')  AND EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Z' AND COLUMN_NAME = 'A')  BEGIN     UPDATE [dbo].[X]          SET Y= (SELECT inst.[A] FROM [dbo].[Z] s WHERE s.[B] = [dbo].[x].[B]); END     GO 
like image 118
Vlad G. Avatar answered Sep 27 '22 19:09

Vlad G.