Search code examples
sql-serverunion-allright-join

2 tables - trying a RIGHT UNION, to replace fields in Table 2


2 tables - trying a RIGHT UNION, to replace fields in Table 2 but still keep all the contents of Table 2. Table1

Table 2

Ultimately what I am trying to do is populate the tcrutm column of table 2 with the entries based on table 1 while using PartNumber and mcno to both be equal in the 2 tables. The code attached does what I need but only returns the column of tcrutm. I would like for table 2 to fully show up with the entries populated. Do I have to recreate the table and overwrite it? I'm not sure. Or could a UNION be used?

Any help is appreciated.

SELECT InsertResults.tcrutm
--PartList.SWITEM,
--PartList.QTY,
--ItemMaster.dsca
FROM FFGD.dbo.CAMWORKS AS InsertResults
RIGHT JOIN FFGD.dbo.BAANExport AS Results ON InsertResults.PartNumber = Results.PartNumber
    AND InsertResults.mcno = Results.mcno

Solution

  • Try with this code

    SELECT T2.[PartNumber],[SWITEM],[QTY],T1.[tcrutm],T2.[mcno] 
    FROM [dbo].[table_2] AS T2
    LEFT OUTER JOIN [dbo].[table_1] AS T1
        ON T2.[PartNumber] = T1.PartNumber AND T2.mcno = T1.mcn
    

    If you want populate the second table use it first and use LEFT JOIN. Or this query is equivalent using RIGHT JOIN

    SELECT T2.[PartNumber],[SWITEM],[QTY],T1.[tcrutm],T2.[mcno]
    FROM [dbo].[table_1] AS T1
    RIGHT OUTER JOIN [dbo].[table_2] AS T2
        ON T1.PartNumber = T2.[PartNumber] AND T1.mcno = T2.mcno
    

    enter image description here

    EDIT:

    Here is the answer to your comment:

    SELECT T2.[PartNumber],[SWITEM],[QTY],T1.[tcrutm],T2.[mcno] 
    INTO [dbo].[table_results]
    FROM [dbo].[table_2] AS T2
    LEFT OUTER JOIN [dbo].[table_1] AS T1
    ON T2.[PartNumber] = T1.PartNumber AND T2.mcno = T1.mcno
    
    SELECT * FROM [dbo].[table_results]
    

    Just add INTO [name_of_your_table] between the fields of your SELECT and FROM