I’d like to sort the rows returned by an UPDATE statement, but there’s no direct way to do this according to the msdn page for the OUTPUT Clause, which says:
SQL Server does not guarantee the order in which rows are processed and returned by DML statements using the OUTPUT clause.
Since I can’t just tack “order by” onto my original query, my next approach is to just put the results into a temporary table or table variable, and then select and order from that. I should be able to figure out a solution using temporary tables, but I don’t think I’ve ever used a table variable before. Is there a reason to prefer one over the other in this context? Or is there a better way to get sorted results from an OUTPUT clause (i.e. w/out using a temp table or table variable)?
The DB platform is SQL Server 2005.
Here’s the original query; I want to sort on the ReleaseDate field.
Update dbo.WFItem
Set ApprovedDate = getdate()
Output inserted.WFItemID, inserted.Title, inserted.Teaser
Where ApprovedDate is null
The table it runs against looks something like this:
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]
I guess your only option would be to turn the
OUTPUTclause into anOUTPUT INTOand store the values in a temporary (in-memory) table and sort them there, when selecting from the temporary table.and then change your UPDATE statement to be:
and then select from the temporary table:
Marc