For the sake of argument, let's just say I have to create a local variable containing a SQL query that has an INSERT:
DECLARE @insert NVARCHAR(MAX) SELECT @insert = 'INSERT INTO [dbo].[' + @table + '] VALUES... EXEC (@insert)
This INSERT is also going to contain a column value:
DECLARE @insert NVARCHAR(MAX) SELECT @insert = 'INSERT INTO [dbo].[' + @table + '] VALUES (N''' + @message + ''')' EXEC (@insert)
Now, I'm obviously concerned about an injection attack, and would like to ensure that @message's value can't make @insert's value malicious or malformed as a query to EXEC.
This brings us to my question: is escaping the ' characters in @message sufficient? Are there any other characters that could appear in @message that could escape out?
Example:
DECLARE @insert NVARCHAR(MAX) SELECT @message = REPLACE(@message,'''','''''') SELECT @insert = 'INSERT INTO [dbo].[' + @table + '] VALUES (N''' + @message + ''')' EXEC (@insert)
(When I say "have to", this is because my query is in a stored procedure, and this stored procedure accepts @table, which is the destination table to INSERT into. I'm not interested in discussing my architecture or why the table to INSERT into is "dynamically" specified via a procedure parameter. Please refrain from commenting on this unless there's another way besides EXEC()ing a query to specify a table to INSERT into when then table name is received as a procedure parameter.)