共用方式為


使用預存程序修改資料

適用於:.NET Framework .NET .NET Standard

下載 ADO.NET

預存程序 (Stored Procedure) 可以接受資料做為輸入參數,也可以將資料以輸出參數、結果集 (Result Set) 或傳回值的形式傳回。 下列的範例說明 Microsoft SqlClient Data Provider for SQL Server 如何傳送及接收輸入參數、輸出參數和傳回值。 此範例會將新記錄插入至主索引鍵資料行為識別欄位的資料表。

注意

如果您透過 SqlDataAdapter 使用預存程序來編輯或刪除資料,請確定您未在預存程序定義中使用 SET NOCOUNT ON。 因為這樣會讓傳回的受影響資料列計數成為零,而 DataAdapter 會將它解譯為並行衝突。 在此事件中,系統會擲回 DBConcurrencyException

範例

此範例使用下列預存程序來將新類別插入 NorthwindCategories 資料表。 此預存程序使用 CategoryName 資料行中的值作為輸入參數,並使用 SCOPE_IDENTITY() 函式來擷取識別欄位 CategoryID 的新值,然後在輸出參數中加以傳回。 RETURN 陳述式使用 @@ROWCOUNT 函式來傳回插入的資料列數。

CREATE PROCEDURE dbo.InsertCategory  
  @CategoryName nvarchar(15),  
  @Identity int OUT  
AS  
INSERT INTO Categories (CategoryName) VALUES(@CategoryName)  
SET @Identity = SCOPE_IDENTITY()  
RETURN @@ROWCOUNT  

下列程式碼範例使用以上所示的 InsertCategory 預存程序做為 InsertCommandSqlDataAdapter 的來源。 在呼叫 @IdentityDataSet 方法而將記錄插入至資料庫之後,Update 輸出參數將反映在 SqlDataAdapter 中。 程式碼也會擷取傳回值。

using System;
using System.Data;
using Microsoft.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = GetConnectionString();
        ReturnIdentity(connectionString);
        // Console.ReadLine();
    }

    private static void ReturnIdentity(string connectionString)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            // Create a SqlDataAdapter based on a SELECT query.
            SqlDataAdapter adapter = new SqlDataAdapter(
                "SELECT CategoryID, CategoryName FROM dbo.Categories", connection);

            // Create a SqlCommand to execute the stored procedure.
            adapter.InsertCommand = new SqlCommand("InsertCategory", connection);
            adapter.InsertCommand.CommandType = CommandType.StoredProcedure;

            // Create a parameter for the ReturnValue.
            SqlParameter parameter = adapter.InsertCommand.Parameters.Add("@RowCount", SqlDbType.Int);
            parameter.Direction = ParameterDirection.ReturnValue;

            // Create an input parameter for the CategoryName.
            // You do not need to specify direction for input parameters.
            adapter.InsertCommand.Parameters.Add("@CategoryName", SqlDbType.NChar, 15, "CategoryName");

            // Create an output parameter for the new identity value.
            parameter = adapter.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "CategoryID");
            parameter.Direction = ParameterDirection.Output;

            // Create a DataTable and fill it.
            DataTable categories = new DataTable();
            adapter.Fill(categories);

            // Add a new row.
            DataRow categoryRow = categories.NewRow();
            categoryRow["CategoryName"] = "New Beverages";
            categories.Rows.Add(categoryRow);

            // Update the database.
            adapter.Update(categories);

            // Retrieve the ReturnValue.
            Int rowCount = (Int)adapter.InsertCommand.Parameters["@RowCount"].Value;

            Console.WriteLine("ReturnValue: {0}", rowCount.ToString());
            Console.WriteLine("All Rows:");
            foreach (DataRow row in categories.Rows)
            {
                    Console.WriteLine("  {0}: {1}", row[0], row[1]);
            }
        }
    }

    static private string GetConnectionString()
    {
        // To avoid storing the connection string in your code,
        // you can retrieve it from a configuration file.
        return "Data Source=(local);Initial Catalog=Northwind;Integrated Security=true";
    }
}

請參閱