c# - 从存储过程返回值

标签 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);
}

最佳答案

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

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);

关于c# - 从存储过程返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20664264/

相关文章:

c# - 如何删除命令行的exe部分

c# - 1 个 sql 和 2 个不同的 sqlconnections 使用 c#

sql-server - 如何解决非聚集索引上的插入/删除死锁?

sql - 将选择结果转换为插入脚本 - SQL Server

sql-server - ColdFusion 将不需要的输出参数添加到存储过程调用

mysql - phpMyAdmin 运行和不运行我的存储过程

c# - 什么线程在 silverlight WCF 调用中调用完成的事件处理程序?

c# - Visual Studio 不会从我的 nupkg 中读取 .pdb

sql-server - SQL Server 错误。标识列的显式值....只能在使用列列表且 IDENTITY_INSERT 为 ON 时指定

c# - .NET 3.5 中的新构造函数