SQL Server 动态 = 存储过程中的运算符

Ben*_*enW 1 sql t-sql sql-server stored-procedures

我有一个关于 SQL Server 中的动态运算符的问题。

举个例子,

select * 
from table1 
where field_1 = 'ABC'
Run Code Online (Sandbox Code Playgroud)

我们可以根据参数动态更改 '=' 吗?假设上述查询在一个存储过程中,并且我们有一个名为 的参数@para

我的问题是:

if @para = "x" then the '=' in the above query remains same
if @para = 'y' then '=' should change to '!='
Run Code Online (Sandbox Code Playgroud)

这能做到吗?

查询应该是这样的

select * 
from table1 
where field_1 OPERATOR_FIELD 'ABC'
Run Code Online (Sandbox Code Playgroud)

这个问题背后是有原因的。我有一个大型存储过程,并认为可能有一种简单的方法来动态更改运算符,而不是CASE到处编写语句。

Gor*_*off 5

你可以这样写:

where ((field_1 = 'ABC' and (@param = '=') ) or
       (field_1 <> 'ABC') and (@param = '<>') )
      )
Run Code Online (Sandbox Code Playgroud)

否则,您需要使用动态 SQL。