仅当第一部分未返回任何内容时,才执行第二部分查询

时间:2014-08-05 16:45:21

标签: sql sql-server

这是我的查询。

select * from jobs where status='BUILDING' and Type='SLA' UNION ALL 
select top 1 * from jobs where Scheduled_Time = (select min(Scheduled_Time) from Jobs 
where status='IDLE' and type='SLA')

我是MSSQL的新手并且想知道如何让这个查询工作,这样如果第一个查询(在UNION ALL之前)没有返回null,那么第二个查询将不会运行?同样,第二个查询应该仅在第一个查询返回null时运行。 (显然,UNION ALL不是答案,因为这包括两个结果,我刚用它作为填充物,这将被删除)。

2 个答案:

答案 0 :(得分:3)

IF EXISTS (select * from jobs where status='BUILDING' and Type='SLA')
BEGIN
select * from jobs where status='BUILDING' and Type='SLA' UNION ALL 
select top 1 * from jobs where Scheduled_Time = (select min(Scheduled_Time) from Jobs 
where status='IDLE' and type='SLA')
END

也许这个查询有性能问题,但这就像你说的那样。 为避免性能不佳,您可以将查询更改为:

DECLARE @result1 TABLE (a INT, Type varchar, status varchar)

INSERT INTO @result1
select * from jobs where status='BUILDING' and Type='SLA'

 IF EXISTS (select * from @result1)
    BEGIN
    select * from @result1 UNION ALL 
    select top 1 * from jobs where Scheduled_Time = (select min(Scheduled_Time) from Jobs 
    where status='IDLE' and type='SLA')
    END

<强>更新

这是您在评论中说的正确查询:

IF EXISTS (select * from jobs where status='BUILDING' and Type='SLA')
 BEGIN
 select * from jobs where status='BUILDING' and Type='SLA' 
END 
ELSE
 select top 1 * from jobs where Scheduled_Time = (select min(Scheduled_Time) from Jobs where status='IDLE' and type='SLA')

答案 1 :(得分:0)

我很感激Saman的帮助。您的IF EXISTS帮助我开始。这个查询为我解决了这个问题。只需要添加一个简单的else语句。

IF EXISTS (select * from jobs where status='BUILDING' and Type='SLA') BEGIN select 
* from jobs where status='BUILDING' and Type='SLA' END ELSE select top 1 * from jobs 
where Scheduled_Time = (select min(Scheduled_Time) from Jobs where status='IDLE' and 
type='SLA')