2

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

 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 子句时是否错误?

谢谢

4

3 回答 3

9
select * from dummyTable
where (parm1 = @parm1 OR @parm1 IS NULL)
  and (parm2 = @parm2 OR @parm2 IS NULL)
  and (parm3 = @parm3 OR @parm3 IS NULL)
  ;
于 2013-07-10T20:14:19.363 回答
5

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

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

... your IF clauses ...

EXEC(@query)

HTH。

于 2013-07-10T19:38:15.270 回答
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)
于 2013-07-10T19:55:20.460 回答