我正在创建一个报告工具,用户可以在其中选择一个运算符和 2 个值进行过滤。
我的基本表:
UserID UserName
-------------------------------
1 User1
2 User2
3 User3
4 User4
5 User5
用户可以选择我想这样翻译的运算符:
Option SQL Operator
------------------------------
between column between x and y
like column '%' + x + '%'
greater than column > x
less than column < x
equal to column = x
not equal to column <> x
我在想类似的东西:
... column = ISNULL(@parameter, column)
从某种意义上说,如果您传递一些东西或什么都不传递,它仍然会正确查询。
这是我正在使用的 TSQL (** DOES NOT WORK * ):
declare @bwValue1 varchar(200) = '2', --between value 1
@bwValue2 varchar(200) = '4'; --between value 2
select * from users where
(UserID BETWEEN @bwValue1 AND @bwValue2
OR UserID != @bwValue1
OR UserID = @bwValue1
OR UserID < @bwValue1
OR UserID > @bwValue1
OR UserID LIKE '%' + @bwValue1 + '%');
有没有办法编写一个无论选择哪个运算符都能正确评估语句的 TSQL?
*最终答案*
对于任何好奇的人,这是我最终得出的结论:
declare @fn varchar(200) = 'carl',
@Op varchar(3) = 'bw',
@bwValue1 varchar(200) = '978',
@bwValue2 varchar(200) = '2000'
select * from users where userfirstname like '%' + @fn + '%'
AND ((@Op = 'eq' AND (userid = @bwValue1))
OR (@Op = 'neq' AND (userid <> @bwValue1))
OR (@Op = 'lt' AND (userid < @bwValue1))
OR (@Op = 'gt' AND (userid > @bwValue1))
OR (@Op = 'li' AND (userid like '%' + @bwValue1 + '%'))
OR (@Op = 'bw' AND (userid between @bwValue1 and @bwValue2)))