简体   繁体   中英

Passing '\' (backslash) character to a stored procedure

I have a WinForm application within an Active Directory environment. One of these forms serves as user management, with the user names being stored on a table in a 2008R2 SQL Server DB

CREATE TABLE Users (
    ID int IDENTITY(0,1) PRIMARY KEY,
    DOMAINUSERNAME nvarchar(15) NOT NULL,
    ID_ROLE int NOT NULL,
    USER nvarchar(15) NOT NULL,
    CREATED datetime NOT NULL,
    CONSTRAINT UC_User UNIQUE (DOMAINUSERNAME)
    );

whose values are inserted through a stored procedure

CREATE PROCEDURE spENABLE (
    @DOMAINUSERNAME nvarchar(7),
    @ROLE int,
    @USER nvarchar(15))
AS
    INSERT INTO Users(
        DOMAINUSERNAME,
        ID_ROLE,
        USER,
        CREATED)
    VALUES (
        @DOMAINUSERNAME,
        @ROLE,
        @USER,
        GETDATE())

On the application domain, these are the relevant lines showing how the domain username string is created

string username = txtNewUser.Text.ToUpper();
string DomainUsername = String.Concat(@"MYDOMAIN\", username);
Roles Role = (Roles)cmbRoles.SelectedIndex;

DataBase.EnableUser(DomainUsername, Role, CurrentUser); //calls the sproc

And this is how the stored procedure is being called

public static void EnableUser(string _domainuser, Roles _role, string _currentuser)
{
    using (SqlCommand cmd = new SqlCommand("spENABLE", connection))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@DOMAINUSERNAME", SqlDbType.NVarChar).Value = _domainuser;
        cmd.Parameters.Add("@ROLE", SqlDbType.Int).Value = (int)_role;
        cmd.Parameters.Add("@USER", SqlDbType.NVarChar).Value = _currentuser;
        cmd.ExecuteNonQuery();
    }
}

Now, this is the (to me) unexpected result:

ID  DOMAINUSERNAME  ROLE    USER            CREATED
-------------------------------------------------------------------
1   MYDOMAIN\       0       MYDOMAIN\USER   2018-04-23 15:03:18.040

I'm sure the _domainuser argument is not empty, so the username part of the domain username must be dropped by the stored procedure. On the other hand, the current username - which is built in the same way! - is being correctly inserted. Maybe it has something to do with the constraint?

Thanks in advance.

Try to change the type of the @DOMAINUSERNAME parameter from nvarchar(7) to nvarchar(15) :

CREATE PROCEDURE spENABLE (
    @DOMAINUSERNAME nvarchar(15),
    @ROLE int,
    @USER nvarchar(15))
AS
...

An nvarchar(7) can only store a string with a max length of 7 which explains why the @DOMAINUSERNAME value (but not the @USER value) gets truncated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM