这是公司的一个办法,可以判断参数Null值,无视这个Where控制
但现在还有更好的:http://blog.youkuaiyun.com/cracklibby/article/details/7562587
exec PROCEDURE @year,@month,@area
GO
CREATE procedure ...
@year int,
@month int,
@area varchar(10)
AS
Begin
declare @SQLbase varchar(2000)
declare @SQLLink varchar(2000)
declare @SQLWhere varchar(2000)
set @SQLbase=' select [...],[...],[...],[...],[...]
from [Tab..]'
set @SQLLink=' '
set @SQLWhere='where 1=1 '
if(@year is not null and @year <> '' and @year <> ' ' )
begin
set @SQLWhere=@SQLWhere+' and year([date...]) = '''+@year+''' '
end
if(@month is not null and @month <> '' and @month <> ' ' )
begin
set @SQLWhere=@SQLWhere+' and month([date...]) = '''+@month+''' '
end
if(@area is not null and @area <> '' and @area <> ' ' )
begin
set @SQLWhere=@SQLWhere+' in '''+@area+''' '
end
--select @SQLbase
--select @SQLLink
--select @SQLWhere
exec (@SQLbase+@SQLLink+@SQLWhere)
END
本文介绍了一种在SQL中动态构建Where条件的方法,通过检查参数是否为Null来决定是否加入到查询条件中。此外,还提供了一个具体的存储过程示例,并提到了一个更优的实现方式。
1787

被折叠的 条评论
为什么被折叠?



