Bad Habits to Kick : Using EXEC() instead of sp_executesql
See the full index.
When using dynamic SQL, you have two choices: EXEC() / EXECUTE(), or sp_executesql. Early on my career, I used EXEC() a lot, because it was much easier. I've since learned that sp_executesql is a lot better, for two main reasons:
- You substantially reduce the risk of SQL injection by continuing to pass strongly-typed variables throughout the whole chain. Which do you find more questionable?
DECLARE @foo nvarchar(64) = N'string''; DROP TABLE dbo.table; --'''; DECLARE @sql nvarchar(max) = N'SELECT foo FROM dbo.table WHERE foo = ''' + @foo + ''''; EXEC(@sql);
… or …
DECLARE @foo nvarchar(64) = N'string''; DROP TABLE dbo.table; --'''; DECLARE @sql nvarchar(max) = N'SELECT foo FROM dbo.table WHERE foo = @foo;'; EXEC sys.sp_executesql @sql, N'@foo nvarchar(64)', @foo;
In the latter case, @foo is a parameter all the way through, making it quite difficult to expose yourself to SQL injection. The results will literally look for the following value:
string'; DROP TABLE dbo.table; --'
Which will return an empty result instead of trying to execute two commands on the server. As an added bonus, your query doesn't have to care about doubling-up or quadrupling-up single quotes (like when searching for
LastName = N''O''''Brien'').
- In older versions of SQL Server, it was much more likely that a plan will get re-used, even for dynamic SQL, when using sp_executesql. This is because the statement itself always looks the same to the optimizer – however you can get the same effect using EXEC() in modern versions with things like Forced Parameterization (SQL Server is getting better and better at detecting parameters on its own, even if you don't explicitly declare them).
Now, can you get bitten by parameter sniffing still in either case? Of course. But you can't solve that by switching between EXEC and sp_executesql; it is something you'll need to use OPTIMIZE FOR or RECOMPILE query hints, or maybe even the optimize for ad hoc workloads setting. This behavior is quite similar to how bind variables in Oracle work.
There are going to be cases where your parameters can't simply be passed in directly, such as variable table names. The threat for SQL injection still exists there, but the performance issues are not really relevant – if the query is going to be pulling from a different table potentially each time, you should definitely be using RECOMPILE.
The bottom line is this: query plan reuse is one of your very best friends; concatenation is the long-lost acquaintance from high school that just might steal your lunch.
For some additional info on moving from EXEC to. sp_executesql, see Denis Gobo's post reminding us that simply changing EXEC to sp_executesql is not a silver bullet.
See the full index.