Select from one table and insert to another two table

前端 未结 1 1941
温柔的废话
温柔的废话 2021-01-14 03:59

I am a beginner at SQL and I don\'t know much about Transact-SQL.

I realize this is a newbie question, but I\'m looking for a simple solution.

I have a table

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 04:12

    I think you want something like the below. The temporary table @Output will capture the inserted identities for the first table, then these can be used when inserting to the second table.

    DECLARE @Output TABLE 
    (       FirstTableID    INT NOT NULL PRIMARY KEY, 
            WarehouseCode   VARCHAR(3), 
            CustomerCode    VARCHAR(4)
    )
    INSERT INTO FirstTable (WarehouseCode, CustomerCode)
    OUTPUT inserted.FirstTblID, inserted.WarehouseCode, inserted.CustomerCode INTO @Output
    SELECT  DISTINCT LEFT(LocationCode, 3) [WarehouseCode], CustomerCode
    FROM    [PrimaryTable]
    
    INSERT INTO SecondTable (ItemCode, LocationCode, CustomerCode, FirstTblID)
    SELECT  p.ItemCode,
            p.LocationCode,
            p.CustomerCode, 
            o.FirstTableID
    FROM    [PrimaryTable] p
            INNER JOIN @Output o
                ON LEFT(LocationCode, 3) = WarehouseCode
                AND p.CustomerCode = o.CustomerCode
    

    0 讨论(0)
提交回复
热议问题