MSSQL編號重排常見解決方案

本文介绍在MSSQL中实现编号重排的四种常见方法:使用Update语句、子查询、临时表及CTE(公共表表达式)。通过这些方法可以高效地更新表中的编号字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

--> Title : MSSQL編號重排常見解決方案

--> Author : wufeng4552

--> Date : 2009-11-25

if object_id('[tb]') is not null drop table [tb]

go

create table [tb] (ID int,ID1 nvarchar(6),ID2 sql_variant)

insert into [tb]

select 1,'001',null union all

select 2,'001',null union all

select 3,'001',null union all

select 4,'002',null union all

select 5,'002',null union all

select 6,'002',null

--方法1 Update

declare @id1 varchar(3),@id2 int

update [tb] set @id2=case when @id1=id1 then @id2+1 else 1 end,

id2=@id2,@id1=id1

select * from tb

-->查詢結果

/*

ID ID1 ID2

----------- ------ -----

1 001 1

2 001 2

3 001 3

4 002 1

5 002 2

6 002 3

(6 個資料列受到影響)

*/

--方法2 子查詢

update t set

id2=(select count(*) from [tb] where id1=t.id1 and id<=t.id)

from [tb] t

select * from [tb]

-->查詢結果

/*

ID ID1 ID2

----------- ------ -----

1 001 1

2 001 2

3 001 3

4 002 1

5 002 2

6 002 3

(6 個資料列受到影響)

*/

--方法3 臨時表

if object_id('tempdb..#')is not null drop table #

select *,cnt=identity(int,0,1)into # from tb order by id1,id

update a set id2=b.cnt-c.cnt+1

from [tb] a ,# b,

(select id1,min(cnt)cnt from # group by id1)c

where a.id1=b.id1 and a.id=b.id and b.id1=c.id1

select * from tb

-->查詢結果

/*

ID ID1 ID2

----------- ------ -----

1 001 1

2 001 2

3 001 3

4 002 1

5 002 2

6 002 3

(6 個資料列受到影響)

*/

--方法MSSQL2005 cte

;with cte

as

(select *,cnt=row_number()over(partition by ID1 order by (select 1)) from [tb])

update cte set id2=cnt

select * from tb

-->查詢結果

/*

ID ID1 ID2

----------- ------ -----

1 001 1

2 001 2

3 001 3

4 002 1

5 002 2

6 002 3

(6 個資料列受到影響)

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值