从存储过程返回值

时间:2013-12-18 17:10:24

标签: c# sql-server stored-procedures

我正在尝试从我的存储过程返回数据。这就是我所尝试过的,绝对没有回来。

存储过程:

Declare @Submit_ID as int
Set @Submit_ID = (Select (Max(Sub_ID) + 1) from Sub_Details);
INSERT INTO.....
Return @Submit_ID

C#(2.0)

SqlConnection conn = null;
int subid;
try
{
    conn = new SqlConnection(conn_string);
    SqlCommand cmd = new SqlCommand("INSERT_INTO_MYDB", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    SqlParameter p1 = new SqlParameter("@FirstName", SqlDbType.NVarChar, 255);
    p1.Direction = ParameterDirection.Input;
    p1.Value = txtFirstName.Text;
    cmd.Parameters.Add(p1);

    SqlParameter p2 = new SqlParameter("@LastName", SqlDbType.NVarChar, 255);
    p2.Direction = ParameterDirection.Input;
    p2.Value = txtLastName.Text;
    cmd.Parameters.Add(p2);

    SqlParameter pSub = new SqlParameter("@Sub_ID", SqlDbType.Int);
    pSub.Direction = ParameterDirection.ReturnValue;

    conn.Open();
    cmd.ExecuteNonQuery();

    subid = Convert.ToInt32(pSub);
}

2 个答案:

答案 0 :(得分:4)

您没有将return参数添加到命令中:

SqlParameter pSub = new SqlParameter("@Sub_ID", SqlDbType.Int);
pSub.Direction = ParameterDirection.ReturnValue;

cmd.Parameters.Add(pSub);    // <-------------  add to command

conn.Open();
cmd.ExecuteNonQuery();

subid = Convert.ToInt32(cmd.Parameters["pSub"].Value);

答案 1 :(得分:1)

首先将参数添加到cmd并将.Value用于其值

 cmd.Parameters.Add(pSub);    // add parameters to command
 cmd.ExecuteNonQuery();
 subid = Convert.ToInt32(pSub.Value); // Use .Value