How can I make the following code SQL injection safe? I know that the problem is the following line:
SET @sqlCommand = @sqlCommand + 'Event.Name LIKE ' + '''%' + @name + '%'''
But I don't know how to make it SQL injection safe. I heard something about REPLACE but this doesn't solve the problem as a whole.
CREATE PROCEDURE searchEvents @name VARCHAR(50), @location VARCHAR(20), @postcode CHAR(4), @address VARCHAR(40), @startDate DATETIME, @endDate DATETIME
AS
DECLARE
@sqlCommand NVARCHAR(MAX) = 'SELECT Event.Name, Description, Location.Name AS Location, Postcode, Address, StartDate, EndDate, Website FROM Event JOIN Location ON Event.LocationID = Location.LocationID',
@parameters NVARCHAR(MAX),
@whereIncluded BIT = 0
BEGIN
IF @name IS NOT NULL
BEGIN
IF @whereIncluded = 0
BEGIN
SET @sqlCommand = @sqlCommand + ' WHERE '
SET @whereIncluded = 1
END
ELSE
SET @sqlCommand = @sqlCommand + ' AND '
SET @sqlCommand = @sqlCommand + 'Event.Name LIKE ' + '''%' + @name + '%'''
END
-- It's the same if clause for all parameters like above
SET @parameters = '@p_name VARCHAR(50), @p_location VARCHAR(20), @p_postcode CHAR(4), @p_address VARCHAR(40), @p_startDate DATETIME, @p_endDate DATETIME'
EXEC sp_executesql
@sqlCommand,
@parameters,
@p_name = @name,
@p_location = @location,
@p_postcode = @postcode,
@p_address = @address,
@p_startDate = @startDate,
@p_endDate = @endDate
END