我想做的是这样的事情
DECLARE @operator nvarchar;
SET @operator = 'AND'
SELECT * FROM MyTable
WHERE first_column = "1" @operator second_columnt = "2"
有没有办法实现像那样的逻辑?
答案 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'))