/*
作者:阿牛(牛昆亮) QQ:273352165 MSN:niukl@hotmail.com
声明:可以免费使用,请您保留此信息
如果您有什么改过,记得告诉我!
*/
在我们使用存储过程的时候,有时为了组合查询条件,不得不使用动态查询。比如下面的代码:
create proc usp_search
@city int
as
begin
declare @sql varchar(8000)
set @sql = N'select * from TestTable where 1=1 '
if(@city <> -1)
set @sql = @sql + ' and cityId = @city '
exec sp_execute_sql @sql, N'@city int', @city
end
go
@city int
as
begin
declare @sql varchar(8000)
set @sql = N'select * from TestTable where 1=1 '
if(@city <> -1)
set @sql = @sql + ' and cityId = @city '
exec sp_execute_sql @sql, N'@city int', @city
end
go
如果我们不用动态SQL,则可以改成下面的存储过程:
create proc usp_search
@city int
as
begin
select * from TestTable where 1=1 and (@city = -1 or cityId = @city)
end
go
@city int
as
begin
select * from TestTable where 1=1 and (@city = -1 or cityId = @city)
end
go