从 C# 中的存储过程中检索返回值
本文探讨了如何从 C# 中的存储过程中检索返回值。
让我们考虑以下名为的存储过程"[dbo].[Validate]":
ALTER PROCEDURE [dbo].[Validate] @a varchar(50), @b varchar(50) output AS SET @Password = (SELECT Password FROM dbo.tblUser WHERE Login = @a) RETURN @b
要执行此存储过程并检索返回值,可以使用以下代码:
using System; using System.Data; using System.Data.SqlClient; namespace StoredProcedureReturnValue { class Program { static void Main(string[] args) { // Assuming you have a connection string defined in your app config string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyLocalSQLServer"].ConnectionString; // Create a connection and command object using (SqlConnection SqlConn = new SqlConnection(connectionString)) using (SqlCommand sqlcomm = new SqlCommand("Validate", SqlConn)) { // Specify the stored procedure sqlcomm.CommandType = CommandType.StoredProcedure; // Add input parameters SqlParameter inputParam = new SqlParameter("@a", SqlDbType.VarChar, 50); inputParam.Value = "myUsername"; sqlcomm.Parameters.Add(inputParam); // Add an output parameter to receive the return value SqlParameter outputParam = new SqlParameter("@b", SqlDbType.VarChar, 50); outputParam.Direction = ParameterDirection.ReturnValue; sqlcomm.Parameters.Add(outputParam); // Open the connection and execute the stored procedure SqlConn.Open(); sqlcomm.ExecuteNonQuery(); // Retrieve the output value string returnValue = (string)outputParam.Value; // Do something with the return value Console.WriteLine($"Return value: {returnValue}"); } } } }
Key需要注意的地方:
以上是如何从 C# 中的存储过程中检索返回值?的详细内容。更多信息请关注PHP中文网其他相关文章!