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

社会主义新天地 提交于 2019-12-11 02:34:15

问题


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 there a way to implement a logic like that one ?


回答1:


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


来源:https://stackoverflow.com/questions/3194696/sql-server-can-a-t-sql-operator-be-used-like-a-variable-or-something-like-tha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!