我声明一个变量:
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时,不要关心UserId (选择所有UserId),但是如果@,那么从另一个表中选择一些UserId
发布于 2013-12-02 08:30:34
select * from Table1
where IsUsed = 1
and
(
@Type is null
or UserId in (select UserId in UserTable)
)
发布于 2013-12-02 08:45:00
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,这样您就不必进行这种存在性检查了。
https://stackoverflow.com/questions/20333039
复制