插入时将自动生成的主键插入另一个表

时间:2019-10-03 05:37:07

标签: sql sql-server tsql

我具有通过ODBC连接访问的以下存储过程。

services.AddSingleton<IProcessService>(new ProcessService(refreshInterval*1000,ILogger logger));

我认为这是对的。我想做的是将ALTER PROCEDURE [dbo].[AddTransactions] @Transactions dbo.TransactionData READONLY AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; INSERT INTO Transactions (CustomerId, EmployeeId, VehicleId, ProductId, LocationId, Number, [Site], [Authorization], [TimeStamp], Odometer, PumpNumber, Quantity, UnitPrice, UnitDiscount, TotalAmount, Code) SELECT CustomerId, EmployeeId, VehicleId, ProductId, LocationId, Number, [Site], [Authorization], [TimeStamp], Odometer, PumpNumber, Quantity, UnitPrice, UnitDiscount, TotalAmount, Code FROM @Transactions END 列(由SQL Server创建的标识列)的值插入到另一个表(只有一个外键列的表)中。

我熟悉Transactions.Id,但是SCOPE_IDENTITY参数最多可以包含25行,我想从每个插入的行中插入ID。这可能吗?

1 个答案:

答案 0 :(得分:2)

没有什么可以阻止您在当前过程中进行另一次插入,前提是您可以保留最后插入的ID:

ALTER PROCEDURE [dbo].[AddTransactions]
    @Transactions dbo.TransactionData READONLY
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO Transactions (CustomerId, EmployeeId, VehicleId, ProductId, LocationId,
        Number, [Site], [Authorization], [TimeStamp], Odometer, PumpNumber,
        Quantity, UnitPrice, UnitDiscount, TotalAmount, Code)
    OUTPUT INSERTED.ID
    SELECT CustomerId, EmployeeId, VehicleId, ProductId, LocationId,
        Number, [Site], [Authorization], [TimeStamp], Odometer, PumpNumber,
        Quantity, UnitPrice, UnitDiscount, TotalAmount, Code
    FROM @Transactions

    INSERT INTO SomeOtherTable(Id)
    SELECT ID FROM INSERTED
END