存储过程返回空值

时间:2014-11-02 18:42:47

标签: c# sql-server

我有一个存储过程:

ALTER PROCEDURE usp_ins_usr_mst        
    @USR_NAME VARCHAR(max),        
    @USR_MAIL VARCHAR(max),    
    @USR_CODE INT OUTPUT        
AS        
BEGIN        
    SET NOCOUNT ON;  

    IF NOT EXISTS (SELECT * FROM USR_MST WHERE [USR_mail] = @USR_MAIL )        
    BEGIN        
       INSERT INTO USR_MST([USR_NAME], USR_MAIL) 
       VALUES(@USR_NAME, @USR_MAIL);        
    END        

    SET @USR_CODE = (SELECT USR_CODE FROM USR_MST WHERE USR_MAIL = @USR_MAIL)  ;  
    select @USR_CODE ;  
END 

和C#代码如下:

using (SqlConnection cn = new SqlConnection(cm.sqlCnnString))
{
    cn.Open();
    SqlCommand cmd = new SqlCommand("exec usp_ins_usr_mst @user, @email, @USR_CODE", cn);
    cmd.Parameters.AddWithValue("@user", " ");
    cmd.Parameters.AddWithValue("@email", HttpContext.Current.Session["uid"].ToString());

    cmd.Parameters.Add("@USR_CODE", SqlDbType.Int);
    cmd.Parameters["@USR_CODE"].Direction = ParameterDirection.Output;

    cmd.CommandTimeout = 15000;
    cmd.ExecuteNonQuery();
    cn.Close();

    HttpContext.Current.Session["USR_CODE"] = cmd.Parameters["@USR_CODE"].Value.ToString();
}

但是这个cmd.Parameters["@USR_CODE"].Value.ToString()正在返回空字符串...我无法弄清楚我在哪里以及缺少什么。

2 个答案:

答案 0 :(得分:0)

尝试替换此

SqlCommand cmd = new SqlCommand("exec usp_ins_usr_mst @user,@email,@USR_CODE", cn);

到此(将OUTPUT子句添加到exec)

SqlCommand cmd = new SqlCommand("exec usp_ins_usr_mst @user,@email,@USR_CODE OUTPUT", cn);

create proc #test_proc
(
    @param_in int,
    @param_out int OUTPUT
) as
begin
    set @param_out = @param_in;
end
go

declare
    @out1 int,
    @out2 int;

exec #test_proc 1, @out1;        -- returns NULL
exec #test_proc 1, @out2 OUTPUT; -- returns 1

select @out1;
select @out2;

drop proc #test_proc

答案 1 :(得分:0)

首先将您的程序更改为使用SCOPE_IDENTITY()而不是

ALTER PROCEDURE usp_ins_usr_mst        
@USR_NAME VARCHAR(max),        
@USR_MAIL VARCHAR(max),    
@USR_CODE INT OUTPUT        
AS        
BEGIN        
  SET NOCOUNT ON;  
 IF NOT EXISTS (SELECT * FROM USR_MST WHERE [USR_mail] = @USR_MAIL )        
 BEGIN        
  INSERT INTO USR_MST([USR_NAME],USR_MAIL) VALUES(@USR_NAME,@USR_MAIL);        
 END  

 SELECT @USR_CODE = SCOPE_IDENTITY();   
END 

尝试保持参数名称与过程相同。你做的一个错误;您正在尝试在关闭连接后获取OUTPUT参数值(如下所示);你应该在关闭连接之前得到它。

cn.Close();

Session["USR_CODE"] = cmd.Parameters["@USR_CODE"].Value.ToString();

修改您的代码,如下所示

        SqlCommand cmd = new SqlCommand("dbo.usp_ins_usr_mst", cn);

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@USR_NAME", " ");
        cmd.Parameters.AddWithValue("@USR_MAIL", Session["uid"].ToString());

        cmd.Parameters.Add("@USR_CODE", SqlDbType.Int);
        cmd.Parameters["@USR_CODE"].Direction = ParameterDirection.Output;
        cmd.CommandTimeout = 15000;
        cmd.ExecuteNonQuery();

        Session["USR_CODE"] = cmd.Parameters["@USR_CODE"].Value.ToString();

        cn.Close();