從 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中文網其他相關文章!