T SQL Query在没有返回行时获取结果

时间:2018-04-24 01:39:28

标签: sql sql-server-2008 tsql

这是查询

SELECT NAME,DATE, COUNT(*) AS ROW_COUNT 
FROM STG
WHERE 
DATE='2018-04-23' AND 
NAME='DRAFT'
GROUP BY NAME,DATE 

要求是如果查询没有返回任何行,那么我应该输出'TEST','TODAY'S DATE',0 否则,如果查询返回行,则返回预期的正常输出。

1 个答案:

答案 0 :(得分:1)

嗯,一种方法使用union all

with t as (
      SELECT NAME, DATE, COUNT(*) AS ROW_COUNT 
      FROM STG
      WHERE DATE = '2018-04-23' AND NAME = 'DRAFT'
      GROUP BY NAME, DATE
     )
select *
from t
union all
select name, date, row_count
from (select 'TEST' as name, getdate() as date, 0 as row_count) x
where not exists (select 1 from t);