February 13, 2018 at 12:00 pm
One simply does not introduces Dynamic SQL
without a section on how to prevent SQL Injection.
The basic changes are simple enough to include them in the article and promote good code from the beginning. Parametrize your dynamic strings and validate securable (objects, schemas, databases) names.
DECLARE @DBName AS VARCHAR(20);
SET @DBName = 'Test';
DECLARE @Date AS DATE;
SET @Date = GETDATE();
DECLARE @SQL AS NVARCHAR(2000);
SELECT @SQL =
N'SELECT COUNT(1) ' + CHAR(13)
+ N'FROM ' + QUOTENAME(d.name) + N'.[dbo].[CommonTable] ' + CHAR(13)
+ N'WHERE [InsertDate] = @iDate;'
FROM sys.databases AS d
WHERE d.name = @DBName;
PRINT @SQL;
EXEC sp_executesql @SQL, N'@iDate date', @iDate = @Date;
February 13, 2018 at 1:02 pm
You Shall Not Pass..............un-parameterized user input directly into strings without using sp_executesql properly!
Little known fact, if Sauron had only used a backup for his One Ring, it would have been safe from Hobbit attack.
-------------------------------------------------------------------------------------------------------------------------------------
Please follow Best Practices For Posting On Forums to receive quicker and higher quality responses
Viewing 2 posts - 16 through 16 (of 16 total)
You must be logged in to reply to this topic. Login to reply