-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.

2
  • 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"; Commented May 24, 2021 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' Commented May 24, 2021 at 14:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.