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

新手上路,请多包涵

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

 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'.

原文由 Mohamed T 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 603
1 个回答

用这个 :

 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

我测试了这个并且它有效

原文由 Ardalan Shahgholi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进