Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL : using parameter as an operator

Is there a way to parameterize the arithmetic operators (<, >, =, >=, <=) in T-SQL?

Something like this:

DECLARE @Operator 

SET @Operator = '>=' 

SELECT * 
FROM Table 
WHERE Date @Operator '7/1/2017'

Also, I am testing to add additional parameter using functions EXEC('SELECT SiteLongName, * FROM Reporting.Survey_Details WHERE CallDate ' + @Operator + '''7/1/2017''' + 'and SiteLongName in (select value from dbo.FnSplit(''' + @Site + ''''+'',''+'','')) , but it is erroring out.

like image 535
Arsee Avatar asked Mar 29 '26 20:03

Arsee


1 Answers

You can if you use dynamic SQL.

Example :

DECLARE @Operator VARCHAR(2)

SET @Operator = '>='

EXEC('SELECT * FROM TABLE WHERE Date ' + @Operator +  ' ''7/1/2017''')

As you can see in the example, handling quotes in dynamic SQL can be a pain. Though it's no big deal in your example.

Be aware that without proper care, dynamic SQL open a vulnerability in your system where user could use SQL Injection attacks against your program.

like image 200
AXMIM Avatar answered Apr 02 '26 08:04

AXMIM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!