How does use of sp_executesql with parameters protect against SQL injection?
8
votes
3
answers
4058
views
The following is a dynamic filtering solution that uses **sp_executesql**
IF OBJECT_ID(N'dbo.GetOrders', N'P') IS NOT NULL DROP PROC dbo.GetOrders;
GO
CREATE PROC dbo.GetOrders
@orderid AS INT = NULL,
@custid AS INT = NULL,
@empid AS INT = NULL,
@orderdate AS DATE = NULL
AS
DECLARE @sql AS NVARCHAR(1000);
SET @sql =
N'SELECT orderid, custid, empid, orderdate, filler'
+ N' /* 27702431-107C-478C-8157-6DFCECC148DD */'
+ N' FROM dbo.Orders'
+ N' WHERE 1 = 1'
+ CASE WHEN @orderid IS NOT NULL THEN
N' AND orderid = @oid' ELSE N'' END
+ CASE WHEN @custid IS NOT NULL THEN
N' AND custid = @cid' ELSE N'' END
+ CASE WHEN @empid IS NOT NULL THEN
N' AND empid = @eid' ELSE N'' END
+ CASE WHEN @orderdate IS NOT NULL THEN
N' AND orderdate = @dt' ELSE N'' END;
EXEC sp_executesql
@stmt = @sql,
@params = N'@oid AS INT, @cid AS INT, @eid AS INT, @dt AS DATE',
@oid = @orderid,
@cid = @custid,
@eid = @empid,
@dt = @orderdate;
GO
On p 541 of T-SQL Querying , it says
> Because the dynamic code uses parameters rather than injecting the
> constants into the code, it is not exposed to SQL injection attacks.
How does the use of parameters in sp_executesql protect against SQL injection?
Thank you
Asked by T. Webster
(319 rep)
Jan 2, 2022, 11:23 PM
Last activity: Jul 7, 2023, 06:58 PM
Last activity: Jul 7, 2023, 06:58 PM