Leary
Leary

Reputation: 117

putting if exists as a condition in WHERE

I can't find answers in Google because I don't know the keyword... so this is my query

SELECT col1 
from table1
WHERE col2 in (select col2 from table2 where user_id=@ID)

I'd like to know if it's possible to put if conditional statements... if table2 is null then i'd pull this condition instead

select col1 from table1 <no condition>

like if select col2 from table2 where user_id=@id is null then it'll pull out all the data

can someone help me?

Upvotes: 0

Views: 86

Answers (2)

FrankPl
FrankPl

Reputation: 13315

SELECT table1.col1 
FROM table1 LEFT OUTER JOIN table2 ON table1.col2 = table1.col2 AND table2.user_id = @ID

Upvotes: 1

Sandip Bantawa
Sandip Bantawa

Reputation: 2880

DECLARE @sql VARCHAR(500)

SET @sql = 'SELECT col1 from table1'
IF((select col2 from table2 where user_id=@ID )IS NOT NULL) 
BEGIN
    SET @sql = @sql + ' WHERE col2 in (select col2 from table2 where user_id= ' + CAST(@ID AS VARCHAR) + ' )'
END
EXEC (@sql)

You can use dynamic query for this case according to your requirement

Upvotes: 0

Related Questions