同一表内,各部份行自动重新编号T-SQL处理代码

--同一表内,各部份行自动重新编号T-SQL处理代码

select identity(int,1,1) as id,* into # from DS order by Department

select Department,min(id) as n,max(id) as m into #DMN
from #
group by Department

update DS set DS.[Sequence]=a.id-(d.n-1)
from # as a,#DMN as d
where a.custid=DS.custid and a.Department=d.Department

drop table #
drop table #DMN

--附:DS表生成脚本及执行结果示意图

CREATE TABLE [dbo].[DS] (
[CustId] [int] NOT NULL PRIMARY KEY,
[Department] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[Sequence] [int] NULL
) ON [PRIMARY]

同一表内,各部份行自动重新编号T-SQL处理代码

你可能感兴趣的:(sql,脚本)