tags:

views:

294

answers:

3

Is there a way (or existing library, not necessarily built into .NET) in C# that performs simple SQL string validation?

Scenario: Building update statement to reduce load on SQL load vs. individual statements. In case the string build does something "odd", like ending with a comma for instance, I'd like to be able to validate that the string is correct.

+4  A: 

If you want to validate the SQL using SQL Server, you can do so by adding

SET PARSEONLY ON

before your script, and then

SET PARSEONLY OFF

after your script.


If you need to avoid going to the database, then maybe you can use the assemblies that Microsoft Visual Studio Team System 2008 Database Edition GDR includes (they have code that handles SQL parsing and script generation). If you don't have the database edition or team suite, you can download the trial version to get the assemblies.

Here is a link I found where someone is using these assemblies.

Gabriel McAdams
Surely this still sends data off to SQL though for the validation? I am more looking for something to validate on the logic tier, not on the data tier.
Kyle Rozendo
Yes, but what could be more valid than using SQL Server to do the validation? You could even use a local server to speed it up if you want.
Gabriel McAdams
I think that using a local SQL server for only validation is overkill to the nth degree. Right now, it still sends off to SQL and will return with an error if there's a problem. I want to skip the middle step and validate (at least to a decent degree) on the logic tier.
Kyle Rozendo
I added to my answer, a solution that might work. Check it out.
Gabriel McAdams
Have you seen my modified answer? I really think it's the solution to your problem.
Gabriel McAdams
Thanks, I have accepted it as it is something that can be done. I don't have access to TS DBE, but I know it will work.
Kyle Rozendo
You can download the trial version to get the assemblies.
Gabriel McAdams
A: 

This third party component does a pretty good job of validating sql without going to the server. SqlParser

Craig
A: 

I've noticed that if you declare a new System.Data.SqlClient.SqlConnection object and set the ConnectionString field to a syntactically invalid connection string, it will throw exception, so this would be one way of checking.

System.Data.SqlClient.SqlConnection foo
        = new System.Data.SqlClient.SqlConnection();
foo.ConnectionString = "not a valid connection string"; //exception thrown here
Rice Flour Cookies
As you already wrote, this works only for the ConnectionString, but not for the SQL statement itself.
Oliver
-1: doesn't answer the question at all.
John Saunders
oops, you're right. He said "SQL String", not "SQL Connection String"
Rice Flour Cookies