SQL Server Dynamic SQL - SQL Injection Prevention

Understanding that Parameterized Stored Procedures are the best way to go ... having said that:

If I must use Dynamic SQL (SQL Server) with variable numbers of  tables and fields, how "safe" is it for me to "Clean" the string by using regex (or other function) to ensure that:
1) the input string is limited to a short string (such as 15 characters to prevent buffer overflow errors)
2) only the characters A-Z, a-z, 0-9 and _  are used (no other symbols, semicolons, etc.)

Example SQL Statement:
"SELECT orderID where ProductDescription = '" & CleanedSQLText & "'"

Open in new window

Also, is using QUOTENAME for fieldnames and tablenames considered reasonably safe to prevent SQL Injections as well?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Shaun VermaakTechnical SpecialistCommented:
In code? This is a simple function in C#
public static Boolean checkForSQLInjection(string userInput)

            bool isSQLInjection = false;
            string[] sqlCheckList = { "--",

            string CheckString = userInput.Replace("'", "''");

            for (int i = 0; i <= sqlCheckList.Length - 1; i++)


                if ((CheckString.IndexOf(sqlCheckList[i],

    StringComparison.OrdinalIgnoreCase) >= 0))

                { isSQLInjection = true; }

            return isSQLInjection;

Open in new window

eeyoAuthor Commented:
Thanks for the code, but I was mainly asking the general question that if only letters and number (and underscore) are used in the input text, is it safe?  In other words, if there are no "--", ":" ,"/", etc. is it pretty safe to assume that a SQL injection can't occur?  The problem I see with using a blacklist is that it may too aggressive.  For example, if an appropriate user input string is "I had to drop my cast on the table to begin to create my artwork", it wouldn't pass muster using a blacklist.
Shaun VermaakTechnical SpecialistCommented:
No, it is not. You need to check for a whole bunch of keywords etc.
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Also keep in mind, there's nothing stopping you from using parameters / variables in sql calls as well.

declare @sqlText varchar(50) = 'test description'
SELECT orderID where ProductDescription = @sqlText

Open in new window

Which also integrates fine with .NET:
sqlCommand.CommandText = "SELECT orderID where ProductDescription = @sqlText";
sqlCommand.Parameters.AddWithValue("@sqlText", "test description");

Open in new window

Using that approach you're still completely safe against injection.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
eeyoAuthor Commented:
Snarf0001, this works well for values.  Do you know of any way I can also use parameters for specifying tables and/or fields (unfortunately, these can't be specified design time ... must be run time)?
No, without getting overly complicated there's not a simple way to accomplish that.
I would say best approach is to use both of the methods going on here.

For the actual value, use the parameterized query.  Then the use can type in anything they need, and there's no worry about injection.

For the target table name, you would have to clean the input, but you can be a lot more restrictive as it only has to be a valid table name, so a LOT is excluded.
In your above sample, alphanumeric and underscore being the ONLY ones allowed, are spaces also excluded?  If so, then I can't see that being open to injection.  

But would be curious if @Shaun can think of something I'm overlooking.
eeyoAuthor Commented:
Luckily, spaces are excluded for the table and field names.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.