簡體   English   中英

使用 ExecuteReader 時,C# 從存儲過程中捕獲返回值

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

我試圖從存儲過程中捕獲返回值,它應該返回 1,但下面的 C# 代碼總是顯示 0。

我知道你應該只讀取輸出參數的值和數據讀取器關閉后的返回值,但我正在這樣做,它仍然使用錯誤的值。

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

您忘記指定CommandType.StoredProcedure 默認情況下,命令類型是CommandType.Text ,它不需要返回值。

嘗試添加:

cmd.CommandType = CommandType.StoredProcedure;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM