"Syntax error converting from a character string to uniqueidentifier"
Posted on 2006-07-05
I have a table in my SQL Server 2000 database with a uniqueidentifier column called "token" assigned to each record. I want to be able to look up a particular record using this token.
In Query Analyzer, both of the following SQL statements execute perfectly:
SELECT * FROM mytable WHERE token='165844ae-3610-4ef0-a93b-993be0b0c88d'
SELECT * FROM mytable WHERE token=CONVERT(uniqueidentifier,'165844ae-3610-4ef0-a93b-993be0b0c88d')
However, running either of those from my C# ASP.NET web application causes a server error that reads: "Syntax error converting from a character string to uniqueidentifier." I am running the following from my app using a very basic data manager I have written which works fine oodles of other places:
string strToken = Request.QueryString["id"];
DataSet ds = Data.DataManager.Select("SELECT * FROM mytable WHERE token=CONVERT(uniqueidentifier,'" + strToken + "')");
As an aside, I am aware that feeding something directly from the query string into a SQL statement like that can open you up to SQL injection attacks... I am using regular expressions to check for and prevent that, however.
Thanks for your assistance!