[posted and mailed, please reply in news]
Phil (ph************@hotmail.com) writes:
I'm currently trying to write a program in C# that will allow users to
parametrize their queries.
For instance, I have a query like this:
SELECT * FROM Customers Where Region = @Region AND Gender > @Gender
How can I extract the Parameters names without using String
manipulation (which is not perfect since sql statements can also
contain '@' in LIKE clauses for example)
I tried this way
Dim comm As New OleDbCommand(SqlStatement, myCon)
comm.Prepare()
MsgBox(comm.Parameters.Count.ToString())
comm.Dispose()
myCon.Close()
but this always return me 0 (zero)
C#? That looks like Visual Basic to me. :-?
IF I understand you correctly, you have a query string like:
SELECT * FROM tbl WHERE @a LIKE '@abc%' AND @bulle = 98
And you want to find @a and @bulle but not @abc? There is no support for
this in ADO .Net, but you would have to parse that string yourself. While
T-SQL is very quirky language to parse completely, this particular case
is not that rough: Traverse the string character by character (which
should be a lot easier in C# I guess, and when you encounter any @, ', "
and /* and -- you have a state change. If you see a ', you are blind to
everything but a new ', same goes for ". If you see /*, you look for */.
And if you see @, you continue until till you see a character that is
not legal in an identifier.
There is still a tricky part or two. Your parser must not misbehave if
fed illegal SQL. And how to handle of the users have entered a variable
in a place where a variable is not permitted, for instance in for a
table name. And most of all: how do you know the data type of the variable?
I think it is somewhere you need to sit down and reconsider whether it
is actually worth the effort.
--
Erland Sommarskog, SQL Server MVP,
es****@sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp