简体   繁体   English

使用 ExecuteReader 时,C# 从存储过程中捕获返回值

[英]C# capture return value from stored proc when using ExecuteReader

I'm trying to capture the return value from a stored proc, it should return 1, but the below C# code always shows 0 instead.我试图从存储过程中捕获返回值,它应该返回 1,但下面的 C# 代码总是显示 0。

I do know that you should only read values of output paramers and the return value AFTER the datareader has been closed, but I am doing that and it still is using the wrong value.我知道你应该只读取输出参数的值和数据读取器关闭后的返回值,但我正在这样做,它仍然使用错误的值。

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                con.Open();

                con.InfoMessage += (object obj, SqlInfoMessageEventArgs e) => {
                    spPrintOutput2.Add(e.Message);
                };

                SqlCommand cmd = new SqlCommand(sql, con);
                cmd.CommandTimeout = 60 * 60;   // 1 hour timeout
                cmd.Parameters.Add("@returnValue", System.Data.SqlDbType.Int).Direction
                    = System.Data.ParameterDirection.ReturnValue;

                using (SqlDataReader dataReader = cmd.ExecuteReader())
                {
                    do
                    {
                        while (dataReader.Read())
                            spPrintOutput2.Add(dataReader[0].ToString());
                    } while (dataReader.NextResult());
                }

                spReturnValue = (int)cmd.Parameters["@returnValue"].Value;  // *** Should be 1 but it is 0

                cmd.Dispose();
            }

You forgot to specify CommandType.StoredProcedure .您忘记指定CommandType.StoredProcedure By default the command type is CommandType.Text , which does not expect a return value.默认情况下,命令类型是CommandType.Text ,它不需要返回值。

Try adding:尝试添加:

cmd.CommandType = CommandType.StoredProcedure;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM