在以前的SQL SERVER中,存储过程和自定义函数只允许传递标量参数。SQL SERVER 2008中允许定义自定义表类型,并传递给存储过程或自定义函数。
CREATE TABLE Inventory
(product_id int PRIMARY KEY,
product_name varchar(50) NOT NULL,
quantity int DEFAULT(0))
GO
INSERT INTO Inventory VALUES(1,'Meta flavored dog shampoo',150)
INSERT INTO Inventory VALUES(2,'Generic canine nail clippers',261)
INSERT INTO Inventory VALUES(3,'Canine paw scissors',89)
GO
现在我们创建一个用户自定义表类型,它描述了我们要传递给存储过程的表:
CREATE TYPE OrderType AS
TABLE(order_item_id int PRIMARY KEY,
product_id int NOT NULL,
quantity int NOT NULL CHECK (quantity>=1),
gift_wrap BIT DEFAULT (0))
我们创建一个存储过程,用到前面定义的表参数
CREATE PROCEDURE UpdateInventory(@myOrder OrderType READONLY)
AS
BEGIN
UPDATE Inventory
set Inventory.quantity-=mo.quantity
From Inventory
INNER JOIN @myOrder mo
ON (mo.product_id=Inventory.product_id)
END
注意:READONLY标示表变量,不能省略
下面为调用的实例
DECLARE @myOrder OrderType
INSERT INTO @myOrder VALUES(1,1,10,0)
INSERT INTO @myOrder VALUES(2,3,5,0)
exec UpdateInventory @myOrder