在 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中文网其他相关文章!