Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from one table and insert to another two table

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 with some columns (locationCode, CustomerCode).

Primary table

    ItemCode    locationCode    CustomerCode
    I001        001001          C001 
    I002        001002          C001    
    I003        001001          C002
    I004        002001          C002

I want to select data from this table and insert to two others table.

First table

firstTblId(autoIncrement)  warehouseCode  CustomerCode
       1                       001           C001   
       2                       001           C002
       3                       002           C002

warehouseCode is a combination of first three characters from locationCode

Data in first table are grouped by first three char of locationCode and Customer Code

second table

secondTblId
(autoIncrement)  ItemCode  locationCode  CustomerCode   firstTblId(FK)
      1            I001       001001        C001            1
      2            I002       001002        C001            1
      3            I003       001001        C002            2
      4            I004       002001        C002            3

So, how can I insert first table and second table by selecting primary table's rows with SQL??

Thanks you for all of your replies.

like image 483
NNNN Avatar asked Dec 08 '25 21:12

NNNN


1 Answers

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
like image 139
GarethD Avatar answered Dec 10 '25 09:12

GarethD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!