在sql中构建基于null / not null参数的where子句

时间:2013-07-10 19:34:24

标签: sql sql-server stored-procedures

我正在尝试创建一个存储过程,它将根据输入返回记录。如果所有输入参数都为null,则返回整个表,否则使用参数并返回记录:

 create procedure getRecords @parm1 varchar(10) = null, @parm2 varchar(10) = null, @parm3 varchar(10) = null
 as
 declare @whereClause varchar(500)
 set @whereClause = ' where 1 = 1 '

 if (@parm1 is null and @parm2 is null and @parm3 is null)
    select * from dummyTable
 else
    begin
      if (@parm1 is not null)
         set @whereClause += 'and parm1 = ' + '' + @parm1 + ''
      if (@parm2 is not null)
         set @whereClause += 'and parm2 = ' + '' + @parm2 + ''
      if (@parm3 is not null)
         set @whereClause += 'and parm3 = ' + '' + @parm3 + ''

      select * from dummyTable @whereClause  <-- Error 
    end

创建此过程时出错是“在条件的上下文中指定的非布尔类型的表达式”

如果构建where子句的方法有误,请评论一下吗?

由于

3 个答案:

答案 0 :(得分:8)

select * from dummyTable
where (parm1 = @parm1 OR @parm1 IS NULL)
  and (parm2 = @parm2 OR @parm2 IS NULL)
  and (parm3 = @parm3 OR @parm3 IS NULL)
  ;

答案 1 :(得分:5)

整个查询应该在varchar中,并且可以使用“EXEC”函数执行。

SET @query = "SELECT * FROM dummyTable WHERE 1=1 "

... your IF clauses ...

EXEC(@query)

HTH。

答案 2 :(得分:0)

尝试这样的事情:

create procedure getRecords @parm1 varchar(10) = null, @parm2 varchar(10) = null, @parm3 varchar(10) = null
as
declare @whereClause varchar(500)
declare @sql varchar(500)

set @sql = 'select * from dummyTable '
set @whereClause = ' where 1 = 1 '

if (@parm1 is null and @parm2 is null and @parm3 is null)
    set @sql = @sql + @whereClause
else
   begin
set @sql = @sql + @whereClause
      if (@parm1 is not null)
        set @sql = @sql + ' and parm1 = ' + '' + @parm1 + ''
      if (@parm2 is not null)
        set @sql = @sql + ' and parm2 = ' + '' + @parm2 + ''
      if (@parm3 is not null)
        set @sql = @sql + ' and parm3 = ' + '' + @parm3 + ''
   end

exec (@sql)