Are the 'inserted' and 'deleted' tables guaranteed to return their records in the same order in an AFTER UPDATE trigger?

旧巷老猫 提交于 2019-12-23 23:10:05

问题


If I have an AFTER UPDATE trigger, will

SELECT * FROM inserted

and

SELECT * FROM deleted

give me back their records in the same order?

I.e. lets say I was able to index into their result sets, will del[5] and ins[5] give me back the matching entries, even if one value of the compound primary key has changed (which would be the reason why an inner join won't work).


回答1:


I don't believe there is any guarantee over the ordering of rows within inserted and deleted - just as there is no ordering guarantee for selecting from any table, without specifying an ORDER BY.


I decided to see if I could produce a script where we could demonstrate the lack of ordering. On my machine (SQL 2008 Dev), I can repeatably run the following script. It outputs 2 rows from inserted and deleted. Note that we don't touch the ID column, and so if the supposition was correct (that they were ordered in some way), then the same IDs should appear in the same order. This is not the case here.

First, the outputs:

ID          D1                      V1
----------- ----------------------- ----------------------------------------------------------------------------------------------------
32          2010-03-01 00:00:00.000 text
60          2010-02-01 00:00:00.000 text

(2 row(s) affected)

ID          D1                      V1
----------- ----------------------- ----------------------------------------------------------------------------------------------------
60          2010-03-01 00:00:00.000 text
32          2010-02-01 00:00:00.000 text

(2 row(s) affected)

And the script that produced this:

create table T1 (
    ID int not null,
    D1 datetime not null,
    V1 varchar(100) not null,
    constraint PK_T1 PRIMARY KEY (D1,ID)
)
go
create index IX_T1_D1 on T1(D1)
go
insert into T1(ID,D1,V1)
select ID,DATEADD(day,ID-1,'20100101'),'text'
from (select ROW_NUMBER() OVER (ORDER BY so1.id) from sysobjects so1,sysobjects so2,sysobjects) t(ID)
go
create trigger T_T1_U on T1 after update
as
begin
    select * from inserted
    select * from deleted
end
go
sp_configure 'disallow results from triggers',0
go
RECONFIGURE
go
update T1 set D1 = DATEADD(month,CASE WHEN DATEPART(month,D1)=2 THEN 1 ELSE -1 END,D1)
where D1 in ('20100201','20100301')
go
sp_configure 'disallow results from triggers',1
go
RECONFIGURE
go
drop table T1
go



回答2:


If you have a PRIMARY KEY on the table (you usually want a id field to be this) then they will always be returned in the same order.



来源:https://stackoverflow.com/questions/4183974/are-the-inserted-and-deleted-tables-guaranteed-to-return-their-records-in-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!