SQL如果select语句没有返回任何行,则执行替代select语句

时间:2011-06-24 10:06:04

标签: sql

基本上,什么是syntex会让我获得标题声明?

If (select statement 1) returns 0 rows THEN (select statement 2) else (select statement 3)

这样sql就会返回语句2或3的结果 我已经找到了一种方法来做到这一点,但到目前为止我发现的任何内容似乎都没有完全解决if要求。

3 个答案:

答案 0 :(得分:20)

IF EXISTS (SELECT field FROM table)
BEGIN
SELECT field FROM table2
END
ELSE
BEGIN
SELECT field FROM table3
END

答案 1 :(得分:1)

你去......

IF ((select count(*) from table1)= 0)
BEGIN
Select * from table2
END
ELSE
BEGIN
SELECT * from table3
END

答案 2 :(得分:1)

很抱歉缺乏反馈意见。办公室里的其他人对此感兴趣并想出了这个:

select * from (
        select *
              , (SELECT Count(*) 
                   FROM users 
                  WHERE version_replace = 59 AND moderated = 1) AS Counter 
          FROM users WHERE version_replace = 59 AND moderated in (0,1)
     ) AS y
where Counter = 0 and Moderated = 0
   or Counter > 0 and Moderated = 1
ORDER By ID DESC

我需要的是什么。