Given the following stored procedure, can I protect against SQL injection in the supplied additional WHERE
condition?
CREATE PROCEDURE [dbo].[ProtectDynamicWhereClause]
(@TableName varchar(50),
@OldestRecordDate varchar(15),
@WhereCondition varchar(250) = NULL)
AS
BEGIN
-- Protect the table name from SQL Injection.
DECLARE @TableNameClean varchar(150) = QUOTENAME(@TableName)
DECLARE @sql nvarchar(4000)
SET @sql =
N'
SELECT * FROM ' + 'dbo.' + @TableNameClean
+ ' WHERE EntryAge > DATEDIFF(year, @OldestRecordDate, GETDATE()) '
IF (@WhereCondition IS NOT NULL)
BEGIN
SET @sql = @sql + ' AND ' + @WhereCondition
END
EXEC sp_executesql @sql, N'@TableNameClean varchar(50), @OldestRecordDate varchar(15)',
@TableNameClean = @TableNameClean, @OldestRecordDate = @OldestRecordDate
END
EXEC ProtectDynamicWhereClause @TableName='CustomerTbl', @OldestRecordDate = '2012-01-01', @WhereCondition = 'CustomerName LIKE ''%Smith%'''
EXEC ProtectDynamicWhereClause @TableName='ProductTbl', @OldestRecordDate = '2010-01-01', @WhereCondition = 'ProductId IN (123, 345, 567)'
Could you please tell me how to protect against SQL injection in this statement when the @WhereCondition
is actually passed-into the stored procedure as a parameter as shown?
SET @sql = @sql + ' AND ' + @WhereCondition
Thank you.