SQLServer 存储过程中不拼接SQL字符串实现多条件查询

以前拼接的写法

set @sql=' select * from table where 1=1 '

if (@addDate is not null) 

     set @sql = @sql+' and  addDate = '+ @addDate + '  ' 
if (@name <>'' and is not null) 
    set @sql = @sql+ ' and name = ' + @name + ' '
exec(@sql)

下面是 不采用拼接sql字符串实现多条件查询解决方

第一种写法是 感觉代码有些冗余
if (@addDate is not null) and (@name <> '') 
      select * from table where addDate = @addDate and name = @name
else if (@addDate is not null) and (@name ='') 
      select * from table where addDate = @addDate
else if(@addDate is  null) and (@name <> '') 
      select * from table where and name = @name
else if(@addDate is  null) and (@name = '')
select * from table

第二种写法是

select * from table where (addDate = @addDate or @addDate is null) and (name = @name or @name = '')
第三种写法是

SELECT * FROM table where addDate = CASE @addDate IS NULL THEN addDate ELSE @addDate END,name = CASE @name WHEN '' THEN name ELSE @name END

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 &#39;EastRiver&#39; 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...