Sunday, February 19, 2012

How to use a backslash "\" in a sql statement

This seems absolutely ridiculous, but I cannot make this work.

string SQLStatement ="select * from [ITData].[AD\\user].[JDDB_ChangeRequests] where requesterid='" + EMPLID +"' and JobID='" + JobID +"'";

DataSet dsPending=newDataSet("Pending");

SqlDataAdapter da =newSqlDataAdapter(SQLStatement, ConnString);

When the SQLStatement is executed, I get an error because it is looking for[AD\\user]instead of[AD\user]with a single backslash. If I put single \ in the code I get invalid escape sequence error.

Any ideas anyone?

Thanks!

I am not sure how the tables are organized but you could try using

string SQLStatement ="select * from [ITData].[AD\\user.JDDB_ChangeRequests] where requesterid='" + EMPLID +"' and JobID='" + JobID +"'";

or

string SQLStatement ="select * from [ITData.AD\\user.JDDB_ChangeRequests] where requesterid='" + EMPLID +"' and JobID='" + JobID +"'";

|||

I tried both of those, but the string still passes through with both backslashes. If I displayed the value of SQLStatement to the screen, it would only show one.

|||

The double backslash is needed because you are coding in C#. It's a string escape thing, it has nothing to do with SQL.

string SQLStatement ="select * from [ITData].[AD\\user].[JDDB_ChangeRequests] where requesterid='" + EMPLID +"' and JobID='" + JobID +"'";

is correct. If it is giving you an error, it's unrelated. Please use that and post the exact error message you get (Copy and paste).

|||

Yes I understand that a backslash is an escape character. My problem is that I need to have a single backslash in my sql statement so I can execute it. By putting the double backslash, the query is trying to select from a table calleby AD\\user.JDDB_ChangeRequests instead of AD\user.JDDB_ChangeRequests, which is what the table is actually called.

If I break before the sql statemant executes, this is what the program is trying to execute.

select * from [ITData].[AD\\user].[JDDB_ChangeRequests] where requesterid='1001' and JobID='6'

The error is "could not find table [AD\\user].[JDDB_ChangeRequests]"

|||string sql ="SELECT * FROM [AD\\user].[test]";

DataSet ds=newDataSet("Pending");

SqlDataAdapter da=newSqlDataAdapter(sql,ConnectionString);

da.Fill(ds);

The above code works correctly (I just executed it -- no errors, and the dataset has the correct data in it). And although, the watch window does show the string containing two backslashes, that again, is a C# thing. That is *NOT* what is being sent to SQL Server. The fact that you can not find the table indeed means, there is no "JDDB_ChangeRequests" table within the "AD\user" schema in the "ITData" database (Or perhaps you don't have the rights to view that table?)

No comments:

Post a Comment