內容轉自:http://db001.com/webc/mssqld/20100730197.html
SQL自动编号 创建测试环境
create table test(id int,sort varchar(10))
SQL自动编号 插入测试数据
insert into test select 1,'a' union all select 2,'b' union all select 3,'c' union all select 4,'d' union all select 5,'e'
SQL自动编号 方法1 不借助临时表
select autoid =(select count(*) from test where id <= a.id),* from test a
SQL自动编号 查询结果
autoid id sort ----------------- 1 1 a 2 2 b 3 3 c 4 4 d 5 5 e
SQL自动编号 方法2 借助临时表
select autoid=identity(int,1,1),* into # from test
SQL自动编号 方法2查询结果
select * from # ---------------------- autoid id sort ----------------- 1 1 a 2 2 b 3 3 c 4 4 d 5 5 e
SQL自动编号 建议
实际应用中, 建议使用方法1,这种一般应用在为各类排名中使用。
本文介绍两种在SQL中实现自动编号的方法:一种是直接通过查询计算编号;另一种是借助临时表来实现。这两种方法适用于不同场景,例如排名等功能。
777

被折叠的 条评论
为什么被折叠?



