我有一个简单的存储过程,它在表中插入用户记录,并应该给出其用户ID。
这是存储过程:
Alter proc spRegistration
@UserId nvarchar(10) output,
@Name nvarchar(20),
@EmailAdd nvarchar(20)
as
begin
Declare @Count int;
Declare @ReturnCode int
Select @Count = Count(EmailAdd)
from tblAllUsers
where EmailAdd = @EmailAdd
if @Count > 0
begin
Set @ReturnCode = -1
end
else
begin
Set @ReturnCode = 1
Insert into tblAllUsers(Name, EmailAdd)
values(@Name, @EmailAdd)
end
Select @UserId = UserId
from tblAllUsers
where EmailAdd = @EmailAdd
Select @ReturnCode as ReturnCode
end
我尝试将userid
放入如下文本框中:
string CS = ConfigurationManager.ConnectionStrings["hh"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spRegistration", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@EmailAdd", txtEmailAddress.Text);
var UserID = cmd.Parameters.AddWithValue("@UserId", SqlDbType.NVarChar);
UserID.Direction = ParameterDirection.Output;
int ReturnCode = (int)cmd.ExecuteScalar();
if (ReturnCode == -1)
{
lblRegMessage.Text = "This email has already been registered with us.";
}
else
{
lblRegMessage.Text = "You were registered successfully.";
txtUserId.Text=(String)UserID.Value;
}
表格和存储过程太复杂了,为了更好地理解问题,我简化了它.UserId是字母数字。不用担心。
设置断点会对var UserID显示null 我哪里错了?
答案 0 :(得分:1)
您需要在.ToString()
UserID
txtUserId.Text= UserID.Value.ToString();
编辑:
var UserID = cmd.Parameters.AddWithValue("@UserId", SqlDbType.NVarChar,50);