[原创]把SQL的动态查询改成SQL查询

/*
作者:阿牛(牛昆亮) 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

      如果我们不用动态SQL,则可以改成下面的存储过程:

create proc usp_search
@city int
as
begin
    select * from TestTable where 1=1 and (@city = -1 or cityId = @city)
end
go
     
posted @ 2006-04-29 17:24  阿牛  阅读(2018)  评论(0编辑  收藏  举报