if else condition in sql
本文关键字:sql in condition else if | 更新日期: 2023-09-27 18:29:05
我想写一个sql查询,它可以:
if
此查询(select X from table1 where x = 'value1')
有结果返回1 else if (select x from table2 where x = 'value2')
有任何结果返回2否则返回0。
感谢
一种方法是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
是否可以用变量实现:
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
@FLAG
变量将保持值0、1或2,因为表包含或不包含数据。如果第一次选择不包含数据,则运行第二次,如果没有返回数据,则返回0(默认@FLAG
值)。
尽管这不是一个有效的查询,也不是使用类似查询的最佳实践,但这应该有效。
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;
当查询时间较短时,选择案例是解决这种情况的更好方法。但当查询长而复杂时,我喜欢使用用户定义的函数,如:
如果dbo。QueryExecution()为NULL--做点什么其他--做点什么
还有dbo。QueryExecution()可以执行您的查询从表1中选择X,其中X="value1"。
这样就更容易测试和维护查询(至少对我来说更容易)。