当某个参数不传入值时,查询语句中where后面不加相应条件处理

假设,存储过程的两个参数为 @p1,@p2

那么依具存储过程中的写法,也有不同的写法.

SQL code

-- 1,若是采用动态语句 declare @sql varchar ( 1000 ) set @sql = ' select * from tb where 1=1 ' if @p1 is not null set @sql = @sql + ' and field1= ' + @p1 if @p2 is not null set @sql = @sql + ' and field2= ' + @p2 -- 2,若是采用的非动态语句 select * from tb where field1 = case when @p1 is null then field1 else @p1 end and field2 = case when @p2 is null then field2 else @p2 end 

你可能感兴趣的:(数据库技术)