我有一个我正在测试的SQL查询,并运行如下,但我注意到它似乎每次返回不同的数据,然后我意识到它甚至返回不同的行数,当我检查它是否有工作!我已多次运行它,最终的select语句将返回25-32行之间,但这怎么会改变呢?
我正在使用begin tran
和rollback tran
来处理相同的数据,并且不相信这是问题所在。谁能发现我做错了什么?
它适用于表(#AddressToDeleteMasterOfLesserId
),它是Id的对,并在客户地址上设置一个标志(IsPrimaryAddress),如果它存在于表中并且它的对具有标志集。 #AddressToDeleteMasterOfLesserId
已经定义且不会更改。
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
答案 0 :(得分:1)
您的#AddressToDeleteMasterOfLesserId
表必须保留一些对,其中Id that is master
与多个Id to delete
配对,而Ids to delete
的匹配值不同IsPrimaryAddress
在CustomerAddress
表中。
在更新阶段,此类Id that is master
行IsPrimaryAddress
随机更新为1或0,具体取决于选择哪个匹配的Id to delete
行作为新值的来源。
答案 1 :(得分:0)
这种方法在每次运行中不会产生相同输出的唯一方法就是你要在其他方面做其他事情,其他人在此之外做其他事情,或者有可能这会变得不稳定如果您有多个未结交易。如果是后者,和/或测试它,只需运行ROLLBACK TRAN
,直到您收到错误消息,指出没有打开的事务。如果您第一次收到错误,那么您没有任何打开错误。