透過TableAdapter取得預存程序的回傳值

作  者:鄭淑芬 精誠資訊 恆逸教育訓練中心 資深講師
技術分類:.NET程式設計
 

傳回新增資料流水編號的預存程序-InsertProduct

以Northwind範例資料庫為例,如下預存程序InsertProduct會在新增一筆產品資料之後回傳這筆產品的流水編號:

CREATE PROCEDURE InsertProduct
( @ProductName nvarchar(40),@UnitPrice money)
AS
INSERT INTO Products(ProductName, UnitPrice)
VALUES(@ProductName, @UnitPrice)
RETURN @@IDENTITY

建立資料集-NorthwindDataSet.xsd

透過Visual Studio,可在專案或網站中例如Console Application,新增項目時選擇「DataSet」,建立如下的NorthwindDataSet.xsd,透過「Server Explorer」視窗,自Northwind資料庫拖放Product資料表下的資料欄位,產生相關DataTable。再於「ProductsTableAdapter」上點選右鍵,透過「Add Query…」對應到回傳一個值的預存程序InsertProduct。

透過Partial Class取得預存程序的傳回值

Visual Studio會為NorthwindDataSet.xsd中的DataTable/TableAdapter建立對應的類別(儲存在*. NorthwindDataSet.Designer.cs),觀察這個檔案中的程式,您會發現TableAdapter下的每個指令都會依出現順序記錄在名為CommandCollection的集合中,例如InsertProduct這個指令出現在第二個, this.CommandCollection[1]代表的就是它(索引值從0開始)。

但這個集合是Private的,因此外部程式無法存取指令的回傳值,不過沒關係,我們可以建立一個與ProductsTableAdapter同名、同命名空間的部分類別,自行加入額外的Public成員,在本例中是個名為InsertProductReturnValue的唯讀屬性,讓外部程式可以取得所需指令的回傳值。如下:

namespace SPReturnValueApp.NorthwindDataSetTableAdapters
{
    public partial class ProductsTableAdapter
    {
        public int InsertProductReturnValue{
            get {
                    int result = -1;

                    if (this.CommandCollection[1].Parameters["@RETURN_VALUE"].Value != null)
                       result = (int)this.CommandCollection[1].Parameters["@RETURN_VALUE"].Value;

                    return result;
                   }
         }
     }
}

撰寫測試程式

您可以建立一個Console應用程式,撰寫如下測試程式:

namespace SPReturnValueApp
{
  class Program
  {
        static void Main(string[] args)
        {
            NorthwindDataSetTableAdapters.ProductsTableAdapter dap = new NorthwindDataSetTableAdapters.ProductsTableAdapter();
            dap.InsertProduct("咖啡", 20);
            int productId = dap.InsertProductReturnValue;
            Console.WriteLine("新增產品的編號:{0}",productId);
        }
    }
}

首先建立一個ProductsTableAdapter物件-dap,接著呼叫InsertProduct加入一個新產品-產品名稱:咖啡、單價:20,之後便可呼叫新增的唯讀屬性InsertProductReturnValue取出新產品的編號。

Share |

可在課程中了解更多.NET資料存取技術…

相關學習資源︰