0

In MS SQL I am doing this - I think it's working correctly but want to check.

UPDATE BillingInvoice 
SET CustomerId = Customer.CustomerId 
FROM Customer 
WHERE BillingInvoice.CustomerId = Customer.CustomerNum 
      AND BillingInvoice.CreatedBy = 222

This is a migration from an old database, what we are doing is first dumping the old customer number into CustomerId, then joining the Customer table, and getting the PK of the customer table, then finally putting back that PK into CustomerId. It does seem to work but want to check that SQL is processing this correctly.

2
  • 1
    The Customer table has 2 different unique keys - CustomerId and CustomerNum? These are enforced with either primary key constraints, unique key constraints or unique indexes? Does BillingInvoice have a foreign key to Customer? No one but you can know if the query is logically correct according to how you define and use your tables. It does seem suspicious and does suggest a schema flaw. You will, of course, validate the result by comparing the before-update values of the affected rows with the after-update values.
    – SMor
    Commented Jan 25, 2022 at 14:03
  • It's a data migration. CustomerId is the identity / PK. Customernum is just a normal field. It holds the old key.
    – Rob
    Commented Feb 22, 2022 at 13:52

2 Answers 2

3

You can use the OUTPUT clause to see which changes have been made :

UPDATE BillingInvoice 
SET    CustomerId = Customer.CustomerId 
OUTPUT inserted.CustomerId, inserted.CreatedBy, inserted.CustomerId, deleted.CustomerId_OLD
FROM   Customer 
WHERE  BillingInvoice.CustomerId = Customer.CustomerNum 
       AND BillingInvoice.CreatedBy = 222

Alternatively you can put the results of the OUTPUT clause into a table (temporary or table variable) to query it

1

I use this technique:

-- BEGIN the transaciotn here
BEGIN TRAN

-- UPDATE here
UPDATE [AdventureWorks2019].[Person].[PersonPhone]
SET PhoneNumber = '222'
WHERE BusinessEntityID BETWEEN 1 AND 5

-- SELECT the change
SELECT TOP 10 * FROM [AdventureWorks2019].[Person].[PersonPhone]

-- ROLLBACK everything
ROLLBACK TRAN 

-- SELECT if everything was rolled back 
SELECT TOP 10 * FROM [AdventureWorks2019].[Person].[PersonPhone]

Here is the outcome on AdventureWorks2019:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.