SQL Server简化WHERE子句

时间:2016-12-14 19:56:31

标签: sql sql-server tsql

有人可以帮我解决这个样本声明:

declare @test int = 5
declare @temp table (id int, name varchar(20))

insert into @temp
values (1,'John'), (1,'Jenny')

if (@test = 5)
begin
    select * 
    from @temp a
    where a.id = 1
      and a.name ='Jenny'
end
else
begin
    select * 
    from @temp a
    where a.id = 1
end

我很确定在WHERE中只有一个SELECT和IF或CASE会变得更简单。

有什么想法吗?

提前致谢!

1 个答案:

答案 0 :(得分:1)

我想你想要这个:

select a.*
from @temp a
where a.id = 1 and
      (a.name = 'Jenny' or @test <> 5);

注意:如果您预计@test可能是NULL,那么逻辑也需要考虑到这一点。