Using SQL Server I am trying to inject a string into a SQL statement based on an if statement, note that am trying to accomplish this inside a stored procedure.
I am currently getting an error for this code:
Declare @topString varchar(240)
IF @topRecords > 0
SET @topString = 'top 500'
ELSE
SET @topString = ''
SELECT @topString * FROM( //incorrect syntax near FROM
SELECT top 500 c.Id as [Customer Id],....
UNION
SELECT top 500 c.Id as [Customer Id],....
)as table1
Order by 1 desc
Edit
if somethingTrue
@whereCondition = '1 = 1 '
else
@whereCondition = branch = @branch
select * from table
where @whereCondition AND etc...
Correct
for injection inside an if statement go with Jodrell
but if you need a dynamic top then go with what was suggested by Kaf.
thanks both for the help!
You can’t inject statement parts as variables like that, however you can change most values for parameters.
Having a stored procedure perform operations that may require different query plans, based on a parameter is a bad idea, the results of this SP could vary wildly based on the value of the
@topRecordsparameter. You would need to use theRECOMPILEoption to warn the query engine, mitigating much of the benefit of SPs. Have you considered just having two stored procedures?If you want to do it dynamically, you could build the whole statement dynamically, making one big string, then execute that.
You should investigate using
sp_executesqlto execute thestring/VarChar. Then similar queries will benefit from query plan reuse.As ever Sommarskog is a good reference.
Something like this