SQL Server,可以像变量一样使用T-SQL运算符吗?或类似的东西

问题描述:

我想做的就是这样

DECLARE @operator nvarchar;
SET @operator = 'AND'

SELECT * FROM MyTable
WHERE first_column = "1" @operator second_columnt = "2"

有没有办法实现像这样的逻辑?

is there a way to implement a logic like that one ?

您可以使用动态sql来做到这一点:

You can do that using dynamic sql:

declare @query varchar(max)
set @query = 'select * from MyTable where first_column = ''1'' ' +
    @operator + ' second_column = ''2'''
exec (@query)

有时候,语句逻辑就足够了,例如:

Sometimes, where statement logic is sufficient, like:

select  *
from    MyTable
where   (operator = 'AND' and first_column = '1' and second_column = '2')
        or (operator = 'OR' and (first_column = '1' or second_column = '2'))