createproc usp_search @cityint as begin declare@sqlvarchar(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,则可以改成下面的存储过程:
createproc usp_search @cityint as begin select*from TestTable where1=1and (@city=-1or cityId =@city) end go