在C# 中擷取預存程序回傳值
考慮以下預存程序:
ALTER PROCEDURE [dbo].[Validate] @a varchar(50), @b varchar(50) output AS SET @Password = (SELECT Password FROM dbo.tblUser WHERE Login = @a) RETURN @b GO
此流程編譯成功。要執行此查詢並取得回傳值,您可以編寫類似以下內容的程式碼:
using System.Data.SqlClient; using System.Configuration; ... SqlConnection SqlConn = new SqlConnection( ConfigurationManager.ConnectionStrings["MyLocalSQLServer"].ConnectionString.ToString()); System.Data.SqlClient.SqlCommand sqlcomm = new System.Data.SqlClient.SqlCommand("Validate", SqlConn); string returnValue = string.Empty; SqlConn.Open(); sqlcomm.CommandType = CommandType.StoredProcedure; SqlParameter param = new SqlParameter("@a", SqlDbType.VarChar); param.Direction = ParameterDirection.Input; param.Value = Username; sqlcomm.Parameters.Add(param); SqlParameter retval = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar); retval.Direction = ParameterDirection.ReturnValue; sqlcomm.ExecuteNonQuery(); // MISSING string retunvalue = (string)sqlcomm.Parameters["@b"].Value;
請注意,為簡潔起見,已省略異常處理。執行程式碼的最後一行後,返回“null”。為了解決此問題,您忘記了執行查詢。新增 sqlcomm.ExecuteNonQuery();在檢索傳回值之前,如下所示:
using System.Data.SqlClient; using System.Configuration; ... SqlConnection SqlConn = new SqlConnection( ConfigurationManager.ConnectionStrings["MyLocalSQLServer"].ConnectionString.ToString()); System.Data.SqlClient.SqlCommand sqlcomm = new System.Data.SqlClient.SqlCommand("Validate", SqlConn); string returnValue = string.Empty; SqlConn.Open(); sqlcomm.CommandType = CommandType.StoredProcedure; SqlParameter param = new SqlParameter("@a", SqlDbType.VarChar); param.Direction = ParameterDirection.Input; param.Value = Username; sqlcomm.Parameters.Add(param); SqlParameter retval = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar); retval.Direction = ParameterDirection.ReturnValue; sqlcomm.ExecuteNonQuery(); // Include this line to execute the query string retunvalue = (string)sqlcomm.Parameters["@b"].Value;
透過合併此更改,您應該能夠成功從預存程序中擷取傳回值。
以上是如何在 C# 中正確檢索預存程序回傳值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!