-2

I would like to something like the following in SQL Server, is this possible?

SELECT *
FROM (
   if (val == 0) 
     table1
   else 
     table2
)

Nothing like this seems to work, how would you accomplish this?

Dale K
  • 16,372
  • 12
  • 37
  • 62

2 Answers2

1

Just union your 2 queries together and use the parameter condition in the where clause e.g.

SELECT *
FROM table1
WHERE @Val = 0
UNION ALL
SELECT *
FROM table2
WHERE @Val <> 0;

Assuming Val should be @Val (i.e. a variable). The logic doesn't make sense if its a column.

Dale K
  • 16,372
  • 12
  • 37
  • 62
0
IF EXISTS (SELECT * FROM table1 where @Val = 0)   
BEGIN
    SELECT * FROM table1
END
ELSE  
BEGIN
    SELECT * FROM table2
END
  • 1
    While this may be adequate for simple queries, I’m assuming the reason the OP is asking is because they have a more complicated query that they don’t want to repeat. Also, I believe they’ve already established the basis for `@Val`, and so don’t need to introduce a query to validate it. – Jeremy Caney Jun 11 '20 at 01:05
  • 2
    Welcome to Stackoverflow! Please add some explanation along with code snippets so other users can understand how the solution was arrived at. – Ankit Jun 11 '20 at 04:26