I want to write a sql query that does:
if
this query (select X from table1 where x = 'value1')
has result return 1 else if (select x from table2 where x = 'value2')
has any result return 2 else return 0.
Thanks
I want to write a sql query that does:
if
this query (select X from table1 where x = 'value1')
has result return 1 else if (select x from table2 where x = 'value2')
has any result return 2 else return 0.
Thanks
One method is a select
and case
:
select (case when exists (select X from table1 where x = 'value1')
then 1
when exists (select x from table2 where x = 'value2')
then 2
else 0
end) as flag
Is it possible to implement with variables:
DECLARE @FLAG INT = 0;
SELECT @FLAG = 1 FROM table1 WHERE x = 'value1'
IF @FLAG = 0
BEGIN
SELECT @FLAG = 2 FROM table2 WHERE x = 'value2'
END
SELECT @FLAG
The @FLAG
variable will hold the value 0, 1 or 2 as the tables contains or not data. If the 1st select does not contain data, then you run the second, if none return data, then return 0 (default @FLAG
value).
This should work although it's not an efficient query nor a best practice to use queries like that.
select
case when exists (select X from table1 where x = 'value1') then 1
when exists (select x from table2 where x = 'value2') then 2
else 0
end;
Select case is better way to solve this situation when query is short. But when query is long and complex i like to use user defined functions like:
IF dbo.QueryExecution() IS NULL --do something ELSE --do something
And dbo.QueryExecution() can execute your query select X from table1 where x = 'value1'.
On this way it is easier to test and maintain query (at least it is easier to me).