在SQL语句中构建动态where条件

时间:2013-09-30 09:33:14

标签: sql sql-server stored-procedures where-clause dynamic-sql

我想基于存储过程输入构建自定义Where条件,如果不为null,那么我将在语句中使用它们,否则我将不会使用它们。

if @Vendor_Name is not null
    begin 

    set @where += 'Upper(vendors.VENDOR_NAME) LIKE "%"+ UPPER(@Vendor_Name) +"%"'

    end
    else if @Entity is not null
    begin
    set @where += 'AND headers.ORG_ID = @Entity'
    end
select * from table_name where @where

但是我收到了这个错误

An expression of non-boolean type specified in a context where a condition is expected, near 'set'.

3 个答案:

答案 0 :(得分:5)

您不能像在此行中那样简单地将变量放在普通的SQL中:

select * from table_name where @where;

您需要使用动态SQL。所以你可能有类似的东西:

DECLARE @SQL NVARCHAR(MAX) = 'SELECT * FROM Table_Name WHERE 1 = 1 ';
DECLARE @Params NVARCHAR(MAX) = '';

IF @Vendor_Name IS NOT NULL
    BEGIN
        SET @SQL += ' AND UPPER(vendors.VENDOR_NAME) LIKE ''%'' + UPPER(@VendorNameParam) + ''%''';
    END
ELSE IF @Entity IS NOT NULL
    BEGIN
        SET @SQL += ' AND headers.ORG_ID = @EntityParam';
    END;

EXECUTE SP_EXECUTESQL @SQL, N'@VendorNameParam VARCHAR(50), @EntityParam INT', 
                    @VendorNameParam = @Vendor_Name, @EntityParam = @Entity;

我认为你的实际问题更复杂,你为此简化了它,但是如果所有的谓词都是使用IF .. ELSE IF.. ELSE IF添加的,那么你根本不需要动态SQL,你可以使用:< / p>

IF @Vendor_Name IS NOT NULL
    BEGIN
        SELECT  * 
        FROM    Table_Name
        WHERE   UPPER(vendors.VENDOR_NAME) LIKE '%' + UPPER(@Vendor_Name) + '%';
    END
ELSE IF @Entity IS NOT NULL
    BEGIN
        SELECT  * 
        FROM    Table_Name
        WHERE   headers.ORG_ID = @Entity;
    END

答案 1 :(得分:3)

使用此:

Declare @Where NVARCHAR(MAX) 

...... Create your Where

DECLARE @Command NVARCHAR(MAX) 
Set @Command = 'Select * From SEM.tblMeasureCatalog AS MC ' ;

If( @Where <> '' )
   Set @Comand = @Command + ' Where ' + @Where

Execute SP_ExecuteSQL  @Command

我测试了这个并且工作了

答案 2 :(得分:0)

老问题,但想补充一下我刚刚发现的问题

where CASE WHEN @id = 0 THEN 1 ELSE id END = CASE WHEN @id = 0 THEN 1 ELSE @id END

这是来自以下步骤:

where id = @id

检查@id是否为null(或无效)或具有有效值,请使用大小写替换@id:

where id = 
CASE WHEN @id is null
    THEN 0
    ELSE @id
END

这将以

结束
where id = 0 -- if @id is null, still affected your query
where id = @id -- if @id have valid value

因为我们只想在有有效数据的情况下使用此“ where”子句,所以我们也更改了ID

where 
CASE WHEN @id is null
    THEN 0
    ELSE id
END 
= 
CASE WHEN @id is null
    THEN 0
    ELSE @id
END

然后将以

结尾
where 0 = 0 -- if @id is null and it doesn't affect your query
where id = @id -- if @id have valid value

不要忘记id是否为varchar,请将0用作'0'

CASE WHEN @id is null
    THEN '0'
    ELSE id
END 

我在我的项目中使用了它并且运行良好,即使我在一个查询中使用了不止一个。请让我知道此查询是否需要花费大量数据的时间