开发者

SQL Server, Can a T-SQL operator be used like a variable ? Or something like that

开发者 https://www.devze.com 2023-01-06 12:07 出处:网络
What I want to do is something like this DECLARE @operator nvarchar; SET @operator = \'AND\' SELECT * FROM MyTable

What I want to do is something like this

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

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

is th开发者_运维问答ere a way to implement a logic like that one ?


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

精彩评论

暂无评论...
验证码 换一张
取 消