如果变量不为null,则设置where语句

时间:2013-12-02 16:29:33

标签: sql-server

我声明了一个变量:

declare @Type nvarchar(max);

然后我想写一个陈述并在@Type时使用not null

select * from Table1
where IsUsed = 1
if @Type is not 
  and UserId in select UserId in UserTable

这是错误的陈述,我该怎么办呢?


这句话是:当@Type为null然后不关心UserId(选择所有UserId),但如果@Type不为null则从另一个表中选择一些UserId

2 个答案:

答案 0 :(得分:1)

select * 
from Table1 a
left join UserTable b
    on a.UserId = b.UserId
where IsUsed = 1
    and (@type is not null and b.UserId is not null)

但实际上,你应该在UserId上有一个FK,这样你就不必进行那种存在检查。

答案 1 :(得分:0)

select * from Table1
where IsUsed = 1
and 
(
     @Type is null 
     or UserId in (select UserId in UserTable)
)