我有以下两个表
CREATE TABLE Orders
(
OrderID int IDENTITY NOT NULL,
StaffID int NOT NULL,
TotalPrice money NOT NULL,
OrderDateTime dateTime NOT NULL
PRIMARY KEY (OrderID),
FOREIGN KEY (StaffID)
REFERENCES Staff(StaffID)
)
CREATE TABLE OrderDetails
(
OrderDetailID int IDENTITY NOT NULL,
OrderID int NOT NULL,
ItemID int,
ExtrasID int,
ItemQuantity int,
ExtrasQuantity int
PRIMARY KEY (OrderDetailID)
FOREIGN KEY (OrderID)
REFERENCES Orders(OrderID),
FOREIGN KEY (ExtrasID)
REFERENCES Extras(ExtrasID),
FOREIGN KEY (ItemID)
REFERENCES Item(ItemID)
)
我想创建一个存储过程,它将通过将数据插入到两个表中来创建新订单。此过程应采用StaffID,TotalPrice和已购买产品的参数。产品可以是许多项目,许多额外或两者。
有没有什么方法可以将ItemID列表和ExtrasID列表作为参数,然后将正确插入到OrderDetails表中?
答案 0 :(得分:1)
CREATE TYPE dbo.ty_Product_Orders AS Table
(
ItemID INT
,ExtrasID INT
,ItemQuantity INT
,ExtrasQuantity INT
)
GO
现在让你的程序接受该类型的参数。
CREATE PROCEDURE usp_Place_Order
@StaffID INT
,@TotalPrice MONEY
,@Order dbo.ty_Product_Orders READONLY
,@OrderPlaced BIT = 0 OUTPUT
AS
BEGIN
SET NOCOUNT ON;
-- table variable to hold the identity values
DECLARE @OrderDetails TABLE
(
OrderID INT,
ItemID INT
,ExtrasID INT
,ItemQuantity INT
,ExtrasQuantity INT
)
BEGIN TRY
BEGIN TRANSACTION;
-- Insert Orders
INSERT INTO Orders (StaffID , TotalPrice , OrderDateTime)
OUTPUT inserted.OrderID , inserted.ItemID ,inserted.ExtrasID ,
inserted.ItemQuantity ,inserted.ExtrasQuantity
INTO @OrderDetails(OrderID , ItemID , ExtrasID
,ItemQuantity ,ExtrasQuantity)
SELECT @StaffID , @TotalPrice , GETDATE()
FROM @Order
-- insert OrderDetails
INSERT INTO OrderDetails ((OrderID , ItemID , ExtrasID ,ItemQuantity ,ExtrasQuantity)
SELECT OrderID , ItemID , ExtrasID,ItemQuantity ,ExtrasQuantity
FROM @OrderDetails
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF (@@TRANCOUNT <> 0)
ROLLBACK TRANSACTION;
-- Other error logging here
END CATCH
END