SQL:返回Null行(如果存在),否则返回其他行

时间:2014-08-14 14:51:16

标签: sql sql-server tsql

我有以下表格

AccessId PK, 
UserId, 
SecurityId, 
SectionId (nullable)

如果用户对同一securityId有多行。

UserId | SecurityId   | SectionId
-------------------------------------
User 1 | SecurityId 1 | SectionId 1
User 1 | SecurityId 1 | SectionId 2
User 1 | SecurityId 1 | SectionId 3

我希望查询返回所有这3行。 如果我们用Null值替换最后一行Section Id,我希望查询只返回空值的行。

问题是,如果没有定义SectionId,则安全性是应用程序范围的。如果定义了sectionId,则安全性将应用于该特定部分。

4 个答案:

答案 0 :(得分:0)

这是or条件。当=@sectionid时,等式(null)将失败,因此您需要第二个条件:

select *
from   table
where  sectionid = @sectionid
or     (sectionid is null and @sectionid is null)

答案 1 :(得分:0)

它是两个独立的查询 - 使用一个union和一个条件来确保只返回union的一面:

select * from mytable
where SecurityId = ?
and SectionId is null
union all
select * from mytable
where SecurityId = ?
and SectionId is not null
and not exists (
    select * from mytable
    where SecurityId = ?
    and SectionId is null)

答案 2 :(得分:0)

select top (1) with ties t.*
from dbo.Table t
where t.SecurityId = @SecurityId
order by case when t.SectionId is null then 0 else 1 end;

答案 3 :(得分:0)

    declare @t table (AccessId int identity, UserId int, SecurityId int, SectionId int)

insert into @t (UserId, SecurityId, SectionId)
values(1,1,1)
, (1,1,2)
, (1,1,3)
, (2,1,1)
, (2,1,Null)

select *
    from @t
    where AccessId not in 
    (
    select t.AccessId
        from @t t inner join
            (
            select AccessId, UserId, SecurityId, SectionId
                from @t
                where SectionId is null
            ) secnull on t.UserId = secnull.UserId and t.SectionId = secnull.SecurityId
)