MaxPowers
MaxPowers

Reputation: 504

SqlCommand with where clause backslashes

There is a matching record in the DB for DESKTOP-123\\markj. When I execute the code in SQL Server Management Studio, it returns one record.

DECLARE @User NVARCHAR(260) = 'DESKTOP-123\\markj'

SELECT r.RoleName 
FROM dbo.WindowsAuthenticationRole war 
JOIN dbo.[Role] r ON r.RoleId = war.RoleId 
WHERE war.[User] = @User

However this C# code returns 0 records

SqlCommand command = new SqlCommand("SELECT r.RoleName FROM dbo.WindowsAuthenticationRole war JOIN dbo.[Role] r ON r.RoleId = war.RoleId WHERE war.[User] = @User", connection);

command.Parameters.Add("@User", SqlDbType.NVarChar).Value = @"DESKTOP-123\\markj";

How can I get the SQL command in C# to work?

Update

The responses helped me troubleshoot, I actually had the value saved in the DB with two slashes.

Upvotes: -1

Views: 132

Answers (1)

Jawad
Jawad

Reputation: 11364

use either @ without escaping the backslash.. or escape it without @

command.Parameters.Add("@User", SqlDbType.NVarChar).Value = @"DESKTOP-123\markj";

//or
command.Parameters.Add("@User", SqlDbType.NVarChar).Value = "DESKTOP-123\\markj";

Documentation on string interpolation.

Upvotes: 3

Related Questions