CREATE TABLE #t(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Title] [nvarchar](50),
[CreationTime] [datetime] DEFAULT (getdate()),
[OrderIndex] [int],
)
go
insert into #t(title,orderIndex) values('文章A',0)
insert into #t(title,orderIndex) values('文章B',0)
insert into #t(title,orderIndex) values('文章C',2)
insert into #t(title,orderIndex) values('文章D',0)
insert into #t(title,orderIndex) values('文章E',6)
insert into #t(title,orderIndex) values('文章F',3)
insert into #t(title,orderIndex) values('文章G',0)
insert into #t(title,orderIndex) values('文章H',4)
insert into #t(title,orderIndex) values('文章I',0)
select * from #t
------解决方案--------------------
刚才的不对,SORRY. 这个运行过了的: select rowId,Id,Title,CreationTime,OrderIndex from ( select rowId = id,rn = Row_Number() over(order by id) from #t where ID NOT IN (select orderindex from #t) ) A INNER JOIN ( select *,rn = Row_Number() over(order by id) from #t where OrderIndex=0 ) B ON A.rn=B.rn UNION select OrderIndex,* from #t where OrderIndex>0 order by 1
------解决方案--------------------
insert into #t(title,orderIndex) values('文章A',0) insert into #t(title,orderIndex) values('文章B',0) insert into #t(title,orderIndex) values('文章C',2) insert into #t(title,orderIndex) values('文章D',0) insert into #t(title,orderIndex) values('文章E',6) insert into #t(title,orderIndex) values('文章F',3) insert into #t(title,orderIndex) values('文章G',0) insert into #t(title,orderIndex) values('文章H',4)