T-SQL: using a parameter as a statement
Is there a way to parameterize arithmetic operators (<,>, =,> =, <=) in T-SQL?
Something like that:
DECLARE @Operator
SET @Operator = '>='
SELECT *
FROM Table
WHERE Date @Operator '7/1/2017'
Also, I am testing adding an extra 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 this is a bug.
+3
source to share
1 answer
You can 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 doesn't really matter in your example.
Keep in mind that without proper care, dynamic SQL opens up a vulnerability in your system where a user can use SQL Injection to attack your program.
+4
source to share