I need to dynamically create SQL, I have a table like this :
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
query exectued is: SELECT * FROM #Test WHERE 22 BETWEEN 21 AND 50 and Value = '21 AND 50'
results:
+----------+-----------+
| Operator | Value |
+----------+-----------+
| BETWEEN | 21 AND 50 |
+----------+-----------+
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.