如何将值插入到2个表中,其中第二个表需要来自第一个表的Id?

时间:2011-11-19 22:11:12

标签: sql-server stored-procedures

我有一个订购系统,当新订单下达时,它会被插入我的表订单。从那里我想将新的id插入到另一个表重要性中,该表还需要来自名为 ImportanceRating 的第三个表的id。

表格结构:

顺序

  • OrderId uniqueidentifier
  • TimeOrderPlaced datetime
  • ProductId uniqueidentifier
  • EstimatedDeliveryTime datetime

重要性

  • FK_OrderId uniqueidentifier
  • FK_ImpRatingId uniqueidentifier

ImportanceRating

  • ImpRatingId uniqueidentifier
  • RatingTitle varchar(50)

所有这些我想要合并在一个存储过程中。我怎么会这样做呢?

非常欢迎链接到这个主题的优秀指南。

我是SPROC新手

3 个答案:

答案 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)

另一种解决方案是使用触发器而不是自定义存储过程。看看以下链接:

Good example of an insert trigger

Official documentation

答案 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