【问题标题】:How to insert values in to 2 tables, where the 2nd table need an Id from the 1st table?如何将值插入到 2 个表中,其中第 2 个表需要第 1 个表的 Id?
【发布时间】:2011-11-22 01:53:50
【问题描述】:

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

表结构:

订购

  • OrderId 唯一标识符
  • TimeOrderPlaced 日期时间
  • ProductId 唯一标识符
  • 预计交付时间日期时间

重要性

  • FK_OrderId 唯一标识符
  • FK_ImpRatingId 唯一标识符

重要性评级

  • ImpRatingId 唯一标识符
  • RatingTitle varchar(50)

我希望将所有这些合并到 1 个存储过程中。我该怎么办?

非常欢迎提供有关该主题的优秀指南的链接。

我是 SPROC 新手

【问题讨论】:

  • 请显示表结构和 SQL 语句...没有它就不可能用示例 SPROC 来回答...
  • @MarkByers - 这是一个新的阳痿产品,叫做SPROC。
  • @MarkByers 你不喜欢吗?

标签: sql-server stored-procedures


【解决方案1】:

你能试试这个吗?:

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

【讨论】:

  • 更新了我的帖子。现在列出表格及其列时可能会对您有所帮助。
【解决方案2】:

你可以试试这个方法吗:

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

【讨论】:

    猜你喜欢
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2012-04-01
    相关资源
    最近更新 更多