[英]Dynamic SQL based on values in table
I need to dynamically create SQL, I have a table like this : 我需要动态创建SQL,我有一个像这样的表:
Operator Value
BETWEEN 0 AND 21
BETWEEN 21 AND 50
I need to write a query that will basically execute: 我需要编写一个将基本执行的查询:
SELECT * FROM tbl
WHERE 22 Operator Value
And this should return the second row of the table above. 这应该返回上表的第二行。
You can go with this, give it a try 您可以尝试一下,尝试一下
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 extrester: http: //rextester.com/OJTIW53082
query exectued is: SELECT * FROM #Test WHERE 22 BETWEEN 21 AND 50 and Value = '21 AND 50'
执行的查询是: SELECT * FROM #Test WHERE 22 BETWEEN 21 AND 50 and Value = '21 AND 50'
results: 结果:
+----------+-----------+
| Operator | Value |
+----------+-----------+
| BETWEEN | 21 AND 50 |
+----------+-----------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.