Link to home
Start Free TrialLog in
Avatar of CAMPzxzxDeathzxzx
CAMPzxzxDeathzxzx

asked on

I need to find orphan records and update values to 0

Here's my try..

SELECT SalesUserID INTO Temp001 FROM [dbo].[Organization]
WHERE NOT EXISTS 
  (SELECT * FROM [dbo].[Users] WHERE UserID = SalesUserID)

Update [Organization]
    Inner Join Temp_Organization
        On Temp_Organization.SalesUserID = [Organization].SalesUserID
Set SalesUserID = 0

Open in new window

Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

If this truly is SQL Server, the UPDATE with a JOIN happens like this:

UPDATE A
SET ...
FROM Table1 A
JOIN Table2 B ON ...

Open in new window


For your specific case, if you do not need to do the intermediate step, you actually can do the UPDATE using the original WHERE NOT EXISTS.

UPDATE [dbo].[Organization]
SET SalesUserID  = 0
WHERE NOT EXISTS (
  SELECT 1 FROM [dbo].[Users]
  WHERE UserID = SalesUserID
) AND SalesUserID <> 0

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CAMPzxzxDeathzxzx
CAMPzxzxDeathzxzx

ASKER

Thanks