'How to compare two SQL tables and insert the difference using PowerShell

I have total of 3 SQL Server tables called Temp_Hold_Inv, Hold_Inv and Daily_Proc.

Temp_Hold_Inv contains the latest data, Hold_Inv contain not up-to-date data.

I'm just wondering how can I compare between the Temp_Hold_Inv and Hold_inv table and if there is a difference then insert only the difference to Hold_Inv, Daily_Proc tables and add value in their additional columns.

Currently here is how my tables columns look like. Also here is how it should look when there is a new user aka difference in Temp_Hold_Inv table and insert it to the other two tables.

Temp_Hold_Inv

Hold    EmpId     Source         Exist      Type
KLM     KLMNOE    [email protected]    Yes        Email

Hold_Inv

Id    Hold      EmpId      Source       Type     CreatedDate 
1     KLM      KLMNOE    [email protected]    Email    04/15/1996

Note: Id is auto-incremented. Also there is no Exist column here. Will need to pass current date automatically.

Daily_Proc

Id    Hold    EmpId    Source          Type    Operation  CreatedDate     Status
1     KLM    KLMNOE    [email protected]    Email     ADD       04/15/1996     New

This is my PowerShell script and I'm able get the difference but not sure how to insert the difference to Hold_Inv and Daily_Proc tables.

$Server = 'ServerName'
$Database = 'DbName'

$query2 = "
    SELECT 'Temp_Hold_Inv' AS SRC, T1.*
FROM (
      SELECT Hold, EmpId, Source FROM Temp_Hold_Inv
      EXCEPT
      SELECT Hold, EmpId, Source FROM Hold_Inv
      ) AS T1
UNION ALL
SELECT 'Hold_Inv' AS SRC, T2.*
FROM (
      SELECT Hold, EmpId, Source FROM Hold_Inv
      EXCEPT
      SELECT Hold, EmpId, Source FROM Temp_Hold_Inv
      ) AS T2
;"

$dbData = Invoke-Sqlcmd -Query $query2 -ServerInstance $Server -Database $Database 

Any help or suggestion will be really appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source