Sql server 当变量不为null或if时设置where语句

Sql server 当变量不为null或if时设置where语句,sql-server,Sql Server,我声明一个变量: declare @Type nvarchar(max); 然后我想写一条语句,当@Type不为null时使用它: 这是错误的说法,我该如何解决这个问题 该语句是:当@Type为null时,则不关心UserId选择所有UserId,但如果@Type不为null,则从另一个表中选择一些UserId select * from Table1 where IsUsed = 1 and ( @Type is null or UserId in (select U

我声明一个变量:

declare @Type nvarchar(max);
然后我想写一条语句,当@Type不为null时使用它:

这是错误的说法,我该如何解决这个问题

该语句是:当@Type为null时,则不关心UserId选择所有UserId,但如果@Type不为null,则从另一个表中选择一些UserId

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

但实际上,用户ID上应该有一个FK,这样就不必进行这种存在性检查。

请注意,他想要的是@Type,而不是null。我多次尝试过你的语句,效果很好,thx@Kiril:是的,我的查询处理的正是该条件。
select * from Table1
where IsUsed = 1
and 
(
     @Type is null 
     or UserId in (select UserId in UserTable)
)
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)