SQL SERVER 2008傳遞表值引數

weixin_34377065發表於2012-11-15

在以前的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

 

 

相關文章