如何对多个表使用最后插入的记录ID

时间:2018-09-23 12:08:57

标签: sql asp.net sql-server sql-server-2008 sql-server-2012

我有3个表,Merchant_Master,Merchant_PaymentDetail和Merchant_refference 主表如下所示,Id是自动增量

  +----+------+------------+----------------+
  | id | mid  | acquirerID |   merchantName |
  +----+------+------------+----------------+
  |  1 | 2345 |          3 |  store 1       |
  +----+------+------------+----------------+

Merchant_PaymentDetail看起来像这样,第一列是AutoIncrement

   +----+-----+--------+-------------+
   | id | mid | BankID |   AccountNo |
   +----+-----+--------+-------------+
   |    |     |        |             |
   +----+-----+--------+-------------+

Merchant_Refference表如下所示,第一列是AutoIncrement

  +----+-----+--------+---------------------+
  | id | mid | Reference 1  |   Reference 2 |
  +----+-----+--------------+---------------+
  |    |     |              |               |
  +----+-----+--------------+---------------+

现在我想使用插入语句将记录插入所有三个表中,但是如何从商人主表到其他两个表中获得相同的中间值 (不是自动递增的),我是否必须使用@@ IDENTITY来实现这一目标,或者还有其他方法。

2 个答案:

答案 0 :(得分:1)

使用您在评论中发布的其他信息,您的存储过程应如下所示:

CREATE PROCEDURE dbo.StoredProcName
  @mid int,
  @acquirerID int,
  ...
AS
BEGIN
  SET NOCOUNT ON;
  SET XACT_ABORT ON;

  BEGIN TRANSACTION;

  INSERT INTO Merchant_Master (mid, acquirerID, merchantName)
    VALUES (@mid, @acquirerID, '...');

  INSERT INTO Merchant_PaymentDetail (mid, BankID, AccountNo)
    VALUES (@mid, ..., ...);

  INSERT INTO Merchant_Refference (mid, [Reference 1], [Reference 2])
    VALUES (@mid, ..., ...);

  COMMIT TRANSACTION;

END;

这样,您将相同的mid插入到事务中的所有三个表中,并且所有IDENTITY(第一列)列都将获得其自动递增的值。

答案 1 :(得分:0)

INSERT INTO Merchant_Master (mid, acquirerID, merchantName)
VALUES...

DECLARE @mid INT = (SELECT mid FROM Merchant_Master WHERE id = SCOPE_IDENTITY())

...然后在您的@mid语句中使用INSERT变量访问其他表