ctsDataTable();
// Create a new ProductsRow instance and set its properties
NorthwindWithSprocs.ProductsRow product = products.NewProductsRow ();
product.ProductName = "New Product";
product.CategoryID = 1; // Beverages
product.Discontinued = false;
// Add the ProductsRow instance to the DataTable
products.AddProductsRow(product);
// Update the DataTable using the Batch Update pattern
productsAPI.Update(products);
// At this point, we can determine the value of the newly-added record''s ProductID
int newlyAddedProductIDValue = product.ProductID;
类似的 ,Products_Update存储过程的UPDATE statement后面也包含一个SELECT statement,如下:
ALTER PROCEDURE dbo.Products_Update
(
@ProductName nvarchar(40),
@SupplierID int,
@CategoryID int,
@QuantityPerUnit nvarchar(20),
@UnitPrice money,
@UnitsInStock smallint,
@UnitsOnOrder smallint,
@ReorderLevel smallint,
@Discontinued bit,
@Original_ProductID int,
@ProductID int
)
AS
SET NOCOUNT OFF;
UPDATE [Products]
SET [ProductName] = @ProductName, [SupplierID] = @SupplierID,
[CategoryID] = @CategoryID, [QuantityPerUnit] = @QuantityPerUnit,
[UnitPrice] = @UnitPrice, [UnitsInStock] = @UnitsInStock,
[UnitsOnOrder] = @UnitsOnOrder, [ReorderLevel] = @ReorderLevel,
[Discontinued] = @Discontinued
WHERE (([ProductID] = @Original_ProductID));
SELECT ProductID, ProductName, SupplierID, CategoryID, QuantityPerUnit,
UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued
FROM Products
WHERE (ProductID = @ProductID)
我们注 意到该存储过程有2个关于ProductID的参数,即@Original_ProductID 和 @ProductID,这样以来我们就可以对主键值进行改动了.举个例子:有一个 employee(雇员)数据库,每条employee记录都用雇员的社保号码作为其主键值.要 想更改某条记录的社保号码,必须提供新的号码以及原始号码.不过对Products表 来说用不着,因为列ProductID是一个唯一标识列(IDENTITY column),不应对其 更改.实际上,Products_Update存储过程里的UPDATE statement并没有包含 ProductID列,因此,如果在UPDATE statement的WHERE字句里使用 @Original_ProductID的话,显得多此一举,而应该使用@ProductID参数.当更新 某个存储过程的参数时,TableAdapter里所有那些调用该存储过程方法都应该进 行更新.
第四步:修改存储过程的参数并更新TableAdapter
由于 @Original_ProductID参数是多余的,让我们将其从Products_Update存储过程里 完全清除.打开Products_Update存储过程,删除@Original_ProductID参数,在 UPDATE statement的WHERE字句里将@Original_ProductID改为@ProductID. 完成 上述修改后,该存储过程里的T-SQL看起来应该和下面的差不多:
ALTER PROCEDURE dbo.Products_Update
(
@ProductName nvarchar(40),
@SupplierID int,
@CategoryID int,
@QuantityPerUnit nvarchar(20),
@UnitPrice money,
@UnitsInStock smallint,
@UnitsOnOrder smallint,
@ReorderLevel smallint,
@Discontinued bit,
@ProductID int
)
AS
SET NOCOUNT OFF;
UPDATE [Products] SET [ProductName] = @ProductName, [SupplierID] = @SupplierID,
[CategoryID] = @CategoryID, [QuantityPerUnit] = @QuantityPerUnit,
[UnitPrice] = @Un
|