简体   繁体   中英

SQL Server Create rows in 3rd table based on columns in 2 tables

I am a SQL Server newbie. I am trying to create test data.

I have a table that contains 10,000 part numbers(Table1).

I have another table that contains warehouses(Table2).

I have a third table(Table3) that will contain a row for every part number/warehouse combination.

Table1 will contain the part numbers, Table2 will contain the 6 warehouses and Table 3 will have a row for each part number/warehouse. That means I will end up with 60,000 rows in Table3. I have looked through all the JOINs and can't seem to find one that does the work. What I want to do is load Table3 with all the part number/warehouse rows with a starting value of 100 in a column called On_Hand. Thank you for your assistance.

INSERT INTO TABLE_3 ( Part_No, Location)    
SELECT Part_No, Location from InventoryTable CROSS JOIN LocationTable WHERE
       order by Part_No

Generate some data:

DECLARE @partNumbers TABLE
(
    PartNumber INT
)

DECLARE @warehouses TABLE
(
    Warehouse VARCHAR(20)
)

DECLARE @partNumberStart INT = 100

-- partnumbers 10000 starting at @partNumberStart  -- for testing.
 INSERT INTO @partNumbers
        SELECT @partNumberStart + ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS ID FROM
       (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x1(x),
       (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x2(x),
       (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x3(x),
       (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x4(x)

--Warehouses 6 generated for testing
INSERT INTO @warehouses
        SELECT x1.x + CAST(ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS VARCHAR(20)) AS ID FROM
       (VALUES('Warehouse ')) x1(x),
       (VALUES(0),(1),(2),(3),(4),(5)) x2(x) --6
       --(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x2(x), --10

Query the data:

SELECT * FROM @warehouses LEFT JOIN @partNumbers on 1=1

--OR
SELECT * FROM @warehouses CROSS JOIN @partNumbers

--OR
SELECT * FROM @warehouses, @partNumbers

You want cross join , used like this:

insert into inventory (part_no, warehouse_id, on_hand)  -- table_3
    select p.Part_No, w.warehouse_id, 500
    from Parts it cross join  -- table_1
         Warehouses w;        -- table_2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM