如果表返回0行,则选择另一个查询

时间:2019-04-01 07:18:11

标签: sql sql-server sql-server-2014

由于我的查询有时会返回0行,所以如果它返回0行,那么我需要选择另一条语句。

select MR.NAME as NAMES,Isnull(cast(sum(MTTR/Month(getdate())) as decimal(18,2)),0) as YTDCURRENTYEAR from #Meantimeresult as MR 
 where YEAR(CONVERT(DATE, '01-' + Month)) = YEAR(GETDATE()) AND MONTH(CONVERT(DATE, '01-' + Month)) <= MONTH(GETDATE()) 
    group by MR.NAMES

第二条语句是

Select NAME='' ,YTDCURRENTYEAR=0

2 个答案:

答案 0 :(得分:2)

IF NOT EXISTS (YOUR FIRST QUERY)
   BEGIN
      YOUR SECOND QUERY
   END

答案 1 :(得分:1)

您可以使用通用表表达式包装第一个查询,并使用union all:

WITH CTE AS
(
    SELECT MR.NAME as NAMES, Isnull(cast(sum(MTTR/Month(getdate())) as decimal(18,2)),0) as YTDCURRENTYEAR 
    FROM #Meantimeresult as MR 
    WHERE YEAR(CONVERT(DATE, '01-' + Month)) = YEAR(GETDATE()) 
    AND MONTH(CONVERT(DATE, '01-' + Month)) <= MONTH(GETDATE()) 
    GROUP BY MR.NAMES
)

SELECT Names, YTDCURRENTYEAR
FROM CTE
UNION ALL
SELECT NAME='' ,YTDCURRENTYEAR=0
WHERE NOT EXISTS(
    SELECT 1 
    FROM CTE
)