My understanding is that the SQL injection risk from contantenating strings together comes from concatenating text into the command string rather than using parameters.
To pass multiple optional paramaters for criteria to be added to a select (anded together), couldn't you use sp_executeSQL to pass all the parameters and only optionally include parameters in the statement to be executed? That is concatenate in the text to add a parameter rather than the value of the parameter. For example, below. I want to do this for 8 or so parameters... Am I missing something fundamental or is this safe?
To pass multiple optional paramaters for criteria to be added to a select (anded together), couldn't you use sp_executeSQL to pass all the parameters and only optionally include parameters in the statement to be executed? That is concatenate in the text to add a parameter rather than the value of the parameter. For example, below. I want to do this for 8 or so parameters... Am I missing something fundamental or is this safe?
Code:
CREATE PROCEDURE dbo.usp_SchedVisit (
@Col1_IN nvarchar(255) = '', @Col2_IN int = -1
)
AS
Declare @SQLString Nvarchar(900)
Declare @ParmDefinition Nvarchar(250)
Declare @Criteria Nvarchar(500)
Set @SQLString = 'SELECT
Table.Col1
Table.Col2
FROM dbo.Table'
/*Just because you pass a bunch of parameters to sp_ExecuteSQL,
that does not mean you have to use them all (for criteria)*/
/*Conditionally add Parameters for values passed in*/
Set @Criteria = ''
IF @Col1_IN <> ''
Set @Criteria = ' Where Col1 = @Col1'
IF @Col2_IN <> -1
Begin
IF LEN(@Criteria) = 0
Set @Criteria = ' Where Col2 = @Col2'
Else
Set @Criteria = @Criteria + ' And ' + 'Col2 = @Col2'
End
Set @SQLString = @SQLString + ' ' + @Criteria
Set @ParmDefinition = N'@Col1 nvarchar(255), @Col2 int'
exec sp_executeSQL @SQLString,
@ParmDefinition,
@Col1 = @Col1_IN,
@Col2 = @Col2_In
;