-1

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.

MaxPowers
  • 474
  • 1
  • 4
  • 18
  • 3
    `There is a matching record in the DB for "DESKTOP-123\markj".` ← You are using the `@` symbol so you only should use one backslash as it is no longer escaped. `@"DESKTOP-123\markj";` – Igor May 24 '21 at 14:00
  • Likewise in Sql Server you do not escape backslash at all in a string (varchar/nvarchar or char nchar). `DECLARE @User NVARCHAR(260) = 'DESKTOP-123\markj'` – Igor May 24 '21 at 14:02

1 Answers1

3

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.

Jawad
  • 11,028
  • 3
  • 24
  • 37