Sql server 2008 r2 SQL Server在if中选择(子查询结果0行使用不同的语句)

Sql server 2008 r2 SQL Server在if中选择(子查询结果0行使用不同的语句),sql-server-2008-r2,subquery,Sql Server 2008 R2,Subquery,我在SQLServer2008R2中有一个表,需要在其中使用子查询获取结果。在某些情况下,子查询不返回任何结果,在这种情况下,我需要这些查询带有null条件 declare @InsID as int =12288 declare @docentry as int = 28 select * from [Table1] a where a.U_InsID = @InsID and a.DocEntry <> @docentry and a.U_ObjectType in

我在SQLServer2008R2中有一个表,需要在其中使用子查询获取结果。在某些情况下,子查询不返回任何结果,在这种情况下,我需要这些查询带有null条件

declare @InsID as int =12288 
declare @docentry as int = 28

select * 
from [Table1] a
where a.U_InsID = @InsID
  and a.DocEntry <> @docentry
  and a.U_ObjectType in ('1','5')
  and (month(a.U_Periode) in 
            (select max(MONTH(U_Periode)) 
             from [Table1] e 
             where e.U_InsID = a.U_InsID 
               and e.DocEntry <> @docentry 
               and (a.U_Status <> '2' or a.U_Status is null))
or (a.U_Periode is null and a.DocEntry <> @docentry and (a.U_Status <> '2' or a.U_Status is null))
)
在这个查询中,我在任何时候都会得到OR结果。。。但我只想在子查询结果为空时得到OR的结果

有什么想法吗

致意
奥利弗

好的,这是一张桌子。该查询排除我正在处理的行,并应返回基于Max DateMonth的结果,如果不存在,则有一行在Period中没有值。我需要得到这个

在我的第一个例子中,where或get这些句子,但在任何时候。。。我一分钟前就想出了一个有效的解决方案。。。但我觉得这不是一个好的,但它正在发挥作用

declare @InsID as int =12288 
declare @docentry as int = 31
declare @var as varchar(30)
--- get the max Month to U_InsID and not the actual Row '31'
set @var = (select max(MONTH(U_Periode)) 
    from [TABLE1] e 
    where e.U_InsID=@InsID
    and e.DocEntry <> @docentry 
    and (e.U_Status <> '2' or e.U_Status is null))

--- If there was no result do this....
if @var is null begin(
select * from [Table1] a
where a.U_InsID = @InsID
and a.DocEntry <> @docentry
and a.U_Periode is null and (a.U_Status <> '2' or a.U_Status is null)
)
end
else   ---- do this if there was a result...
select * from [TABLE1] a
where a.U_InsID = @InsID
and a.DocEntry <> @docentry
and month(a.U_Periode)=@var  and (a.U_Status <> '2' or a.U_Status is null)
我正在寻找一种更平滑的方法,如果。。。否则

我认为在查询本身中应该有一个解决方案。。。 顺致敬意,
奥利弗:你能考虑改写你的问题吗?不清楚,你看到我的答案了吗?