if else condition in sql
This question already has an answer here:
一种方法是select
和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).
这应该工作,虽然它不是一个有效的查询,也不是使用这样的查询的最佳实践。
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;
链接地址: http://www.djcxy.com/p/94346.html
上一篇: 这是MSSQL CASE语句的好场景吗?
下一篇: 如果还有条件在SQL中