我想对UPDATE语句返回的行进行排序,但根据
msdn page for the OUTPUT Clause没有直接的方法来执行此操作,其中说:
sql Server does not guarantee the order in which rows are processed and returned by DML statements using the OUTPUT clause.
由于我不能只将“order by”添加到我的原始查询中,我的下一个方法是将结果放入临时表或表变量,然后从中选择和排序.我应该能够找到使用临时表的解决方案,但我认为我以前从未使用过表变量.在这种情况下,是否有理由偏爱另一个?或者有更好的方法从OUTPUT子句获取排序结果(即使用临时表或表变量w / out)?
这是原始查询;我想对ReleaseDate字段进行排序.
Update dbo.WFItem Set ApprovedDate = getdate() Output inserted.WFItemID,inserted.Title,inserted.Teaser Where ApprovedDate is null
它运行的表看起来像这样:
CREATE TABLE [dbo].[WFItem]( [WFItemID] [int] IDENTITY(1,1) NOT NULL,[Title] [varchar](255) NULL,[Teaser] [varchar](255) NULL,[ReleaseDate] [datetime] NULL,[ApprovedDate] [datetime] NULL,[SentDate] [datetime] NULL,CONSTRAINT [PK_WFItem] PRIMARY KEY CLUSTERED ( [WFItemID] ASC )WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
解决方法
我想你唯一的选择是将OUTPUT子句转换为OUTPUT INTO并将值存储在临时(内存中)表中,并在从临时表中进行选择时对它们进行排序.
DECLARE @UpdateOutputTable TABLE (WFItemID INT,Title VARCHAR(255),Teaser VARCHAR(255),ReleaseDate DATETIME)
然后将您的UPDATE语句更改为:
Update dbo.WFItem Set ApprovedDate = getdate() Output inserted.WFItemID,inserted.Teaser,inserted.ReleaseDate INTO @UpdateOutputTable Where ApprovedDate is null
然后从临时表中选择:
SELECT WFItemID,Title,Teaser FROM @UpdateOutputTable ORDER BY ReleaseDate
渣