[英]Passing '\' (backslash) character to a stored procedure
I have a WinForm application within an Active Directory environment. 我在Active Directory环境中有一个WinForm应用程序。 One of these forms serves as user management, with the user names being stored on a table in a 2008R2 SQL Server DB 这些形式之一用作用户管理,用户名存储在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. 我确定_domainuser
参数不为空,因此存储过程必须删除域用户名的用户名部分。 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)
: 尝试将@DOMAINUSERNAME
参数的类型从nvarchar(7)
更改为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. nvarchar(7)
只能存储最大长度为7的字符串,这说明了为什么@DOMAINUSERNAME
值(而不是@USER
值)会被截断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.