SQLServer - 标识列自增

这几天老是遇到ID列自增的问题!以下是参考CSDN的一些总结

 1/*===================ID列自加 ===*/
 2--
 3create table T1(pk varchar(12),ID int,other varchar(10))
 4truncate table T1
 5insert T1 select '110101001001',Null,'other1'
 6insert T1 select '110101001001',Null,'other2'
 7insert T1 select '110101001001',Null,'other3'
 8insert T1 select '110101001002',Null,'other4'
 9insert T1 select '110101001001',Null,'other5'
10insert T1 select '110101001001',Null,'other6'
11insert T1 select '110101001002',Null,'other7'
12insert T1 select '110101001002',Null,'other8'
13insert T1 select '110101001002',Null,'other9'
14insert T1 select '110101001002',Null,'other0'
15insert T1 select '110101001002',Null,'other'
16--select * from T1
17--要求:将PK相同的ID自加1
18--方法1:将表排序,再填充ID(借助临时表)
19--排序
20 select * into #t from T1 order by pk asc
21 truncate table T1
22 insert into T1 select * from #t
23 drop table #t
24--填充
25 declare @pk varchar(12),@ID int
26 update T1 set @ID=case when @pk=rtrim(pk) then @ID+1 else 1 end,
27 @pk=pk,ID=@ID
28--ok
29 select * from T1
30
31--方法2:添加辅助列实现
32 alter table T1 add TID int identity(1,1)
33 update TA set ID=(select count(*from T1 where pk=TA.pk and TID<=TA.TID)
34 from T1 TA
35 Alter Table T1 Drop Column TID
36--ok 
37 select * from T1 
38
39/*
40要求:T1中的数据如初始状态,有空表T2如下,现将表T1 pk='110101001001'的other填充到表T2的other2中,
41设T2的pk2取自其他表的一个值,ID2自增100,不可以改变T1
42*/

43create table T2(pk2 varchar(5),ID2 int,other2 varchar(10))
44select * from T2
45
46--方法:
47 declare @Dx int
48 select @Dx=Max(ID2) from T2 where pk2='ther1'
49 select pk2=(select top 1 right(other,5from T1),id2 = identity(int,100,100),other into #t from t1 where pk='110101001001'
50 insert into T2 select pk2,id2+@Dx,other from #t
51 drop table #T
52--ok
53 select * from T2
54--在上述T2填充后,对相同条件的数据再填充一次,但ID2在已有数据上递增100
55 declare @Dx int
56 declare @pk varchar(5)
57 select top 1 @pk=right(other,5from T1
58 select @Dx=Max(ID2) from T2 where pk2=@pk
59 select pk2=@pk,id2 = identity(int,100,100),other into #t from t1 where pk='110101001001'
60 insert into T2 select pk2,id2+@Dx,other from #t
61 drop table #T
62--ok
63 select * from T2
64

posted on 2006-07-20 21:07  Lee-hp  阅读(1158)  评论(1)    收藏  举报

努力加载评论中...

导航

点击右上角即可分享
微信分享提示