我有一个订购系统,当新订单下达时,它会被插入我的表订单。从那里我想将新的id插入到另一个表重要性中,该表还需要来自名为 ImportanceRating 的第三个表的id。
表格结构:
顺序
重要性
ImportanceRating
所有这些我想要合并在一个存储过程中。我怎么会这样做呢?
非常欢迎链接到这个主题的优秀指南。
我是SPROC新手
答案 0 :(得分:2)
你可以尝试一下吗?:
CREATE PROCEDURE AddOrderAndRatingSample
-- These are the values you want to insert
@paramTimeOrderPlaced DATETIME
, @paramProductId INT
, @paramEstimatedDeliveryTime DATETIME
, @paramRatingTitle VARCHAR(50)
AS
BEGIN
DECLARE @siOrderId INT
DECLARE @siImpRatingId INT
-- Assuming that `OrderId` in table `Order` is an `identity column`:
INSERT INTO Order (TimeOrderPlaced, ProductId, EstimatedDeliveryTime)
VALUES(@paramTimeOrderPlaced, @paramProductId, @paramEstimatedDeliveryTime)
SET @siOrderId = SCOPE_IDENTITY()
-- Assuming `ImpRatingId` in table `ImportanceRating` is an `identity column`:
INSERT INTO ImportanceRating (RatingTitle)
VALUES(@paramRatingTitle)
SET @siImpRatingId = SCOPE_IDENTITY()
-- And that both `FK_OrderId` and `FK_ImpRatingId`
-- in table `Importance` are not `identity columns`:
INSERT INTO Importance (FK_OrderId, FK_ImpRatingId)
SELECT @siOrderId, @siImpRatingId
END
答案 1 :(得分:0)
答案 2 :(得分:0)
请你试试这个:
DECLARE @OrderId INT
INSERT INTO Order (TimeOrderPlaced, ProductId, EstimatedDeliveryTime)
VALUES(@paramTimeOrderPlaced, @paramProductId, @paramEstimatedDeliveryTime)
SET @OrderId = @@IDENTITY -- Last orderId
INSERT INTO ImportanceRating (RatingTitle)
VALUES(@paramRatingTitle)
INSERT INTO Importance (FK_OrderId, FK_ImpRatingId)
SELECT @OrderId, @@IDENTITY -- Here @@IDENTITY returns last ID of ImportanceRating
-- Each inserting time the global variable @@IDENTITY is set with last IDENTITY value