我需要动态创建SQL,我有一个这样的表:
Operator Value
BETWEEN 0 AND 21
BETWEEN 21 AND 50
我需要编写一个基本上执行的查询:
SELECT * FROM tbl
WHERE 22 Operator Value
这应该返回上表的第二行。
答案 0 :(得分:3)
您可以使用此功能,尝试一下
if object_id('tempdb..#Test') is not null drop table #Test
create table #Test (Operator nvarchar(20), Value nvarchar(20))
insert into #Test (Operator, Value)
values
('BETWEEN', '0 AND 21'),
('BETWEEN', '21 AND 50')
declare @sql nvarchar(max) = 'SELECT * FROM #Test WHERE 22 '
declare @sqlHelper nvarchar(max) =
(select Operator + ' ' + Value
+ ' and Value = '''+Value+''''
from #Test
where 22 <= Cast(RIGHT(Value, 2) as int) and
22 >= Cast(LEFT(Value, 2) as int))
select @sql + @sqlHelper
execute (@sql + @sqlHelper)
rextester:http://rextester.com/OJTIW53082
查询exectued是:SELECT * FROM #Test WHERE 22 BETWEEN 21 AND 50 and Value = '21 AND 50'
结果:
+----------+-----------+
| Operator | Value |
+----------+-----------+
| BETWEEN | 21 AND 50 |
+----------+-----------+