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

时间:2010-07-07 12:37:29

标签: sql-server tsql sql-server-2000 operators

我想做的是这样的事情

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

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

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

1 个答案:

答案 0 :(得分:8)

您可以使用动态sql执行此操作:

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

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

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