I have an SQL query that I am testing, and running as below, but I noticed that it seemed to be returning different data each time, then i realised it was even returning a different amount of rows when i check if it has worked!! I have run it multiple times and the final select statement will return somewhere between 25-32 rows, but how can this change?
I am using begin tran
and rollback tran
to work on the same data, and don't believe this is the issue. Can anyone spot what i have done wrong??
It works on a table(#AddressToDeleteMasterOfLesserId
) which is pairs of Id's and sets a flag (IsPrimaryAddress) on the Customer address if it exists in the table and it's pair has the flag set. #AddressToDeleteMasterOfLesserId
has already been defined and does not change.
begin tran t1
select CustomerAddress.IsPrimaryAddress, p1.[Id that is master],p1.[Id to delete], c2.IsPrimaryAddress
FROM CustomerAddress
join #AddressToDeleteMasterOfLesserId p1 on CustomerAddress.Id=p1.[Id that is master]
join CustomerAddress c2 on p1.[Id to delete]=c2.Id
order by [Id that is master]
--Update primary address
UPDATE CustomerAddress
SET IsPrimaryAddress = CASE WHEN c2.IsPrimaryAddress=1 THEN 1 ELSE 0 END
FROM CustomerAddress
join #AddressToDeleteMasterOfLesserId p1 on CustomerAddress.Id=p1.[Id that is master]
join CustomerAddress c2 on p1.[Id to delete]=c2.Id
select CustomerAddress.IsPrimaryAddress, p1.[Id that is master],p1.[Id to delete], c2.IsPrimaryAddress
FROM CustomerAddress
join #AddressToDeleteMasterOfLesserId p1 on CustomerAddress.Id=p1.[Id that is master]
join CustomerAddress c2 on p1.[Id to delete]=c2.Id
where CustomerAddress.IsPrimaryAddress=0
and c2.IsPrimaryAddress=1
order by [Id that is master]
rollback tran t1