SQL中怎麼自動加入序號

sunrisehy2003 2005-07-30 09:45:49
SQL中怎麼自動加入序號
...全文
191 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
MorningTea 2005-07-30
  • 打赏
  • 举报
回复
A.直接定义,例如
字段类型设置为int型,种子为1,增量。即可。
identity(startvalues,addvalues)
A int identity(35,1)
这就表示字段A的,初始值是35,以1自动增加
也就是说如果你的第一条记录是,那么下一条记录就是36
其中的(35和1)根据自己的实际情况定!!
,对于这种用法,你同时需要了解相关的用法,例如编号重置等等。例如:
1、truncate命令不但会清除所有的数据,还会将IDENTITY的SEED的值恢复到原是值。
truncate table tablename
2、而DBCC CHECKIDENT则更加方便一些,可以在不删除数据的情况下指定SEED的值。
DBCC CHECKIDENT (tablename,reseed,1)

B.就是用identity(data_type,seed,increment),见phantomMan(asp.net VS 数据库)的代码,然后我这里有一段别人写的代码,是在sp,传入identity的seed,以供参考:
create table tt (n nvarchar(10))
insert into tt select 'a' union all select 'b' union all select 'c' union all select 'd'
go
select * from tt
go
create proc d
@id int
as
declare @bh int
set @bh=@id
exec('select identity(int,'+@bh+',1) id,* into #t from tt select * from #t drop table #t')
go
exec d 10
go
drop proc d
drop table tt




phantomMan 2005-07-30
  • 打赏
  • 举报
回复
如果原表没有 identity 字段的话,只能先放入临时表,然后从临时表里面取数据:

select identity(int,1,1) as id, * into #t from table name (条件)
select * from #t
drop table #t

34,873

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧