I always use SqlParameter
to parametrize my queries when calling SQL Server from C#, nevertheless, some of my queries generate an ugly execution plan when using Parameters, in these cases, I rather use hard-coded SQL instead of parameters. Is this a good practice? - maybe not, but performance of the query is great!
I have to use this technique because of Parameter Sniffing in SQL Server.
Now, do anyone has a library to sanitize TSQL code in order to avoid SQL injection? - if not, what should I check to prevent this? (maybe I will end-up creating a NuGet package).
Maybe you know other way to avoid this problem that allows me to keep using SqlParameters?
Thanks!
UPDATE 1: This question comes up because of this other one Improve performance of query with conditional filtering here you can see why I had to come to this solution.
UPDATE 2: In order to complete the context of the question: I have the following query, it is called from C# code using ADO.NET, when using parameters, the query takes from 7s to several minutes to execute depending on the arguments.
SELECT SKU, Store, ColumnA, ColumnB, ColumnC
FROM myTable
WHERE (SKU IN (select * from splitString(@skus)) OR @skus IS NULL)
AND (Store IN (select * from splitString(@stores)) OR @stores IS NULL)
@skus and @stores are strings with concatenated ids like '1,2,3' and splitString
is a database function which transforms that string in a table of 1 column and each item in a row, allowing me to execute IN
filtering in SQL Server.
When executing this very same query without parameters and concatenating directly in the query the ids, it takes between 0s and 5s to execute depending on the ids. I am aware about performace issues when using a function inside the where clause, and I treated that in the final form of the query, but it does not impact on the performance as much as using raw sql. Please read this and take the idea and not literally.
Since I'm being forced to use the second approach because of the performance, how can I avoid SQL Injection?