
sqlserver有3种方式设置自增列,
1
ssms中在图形化界面中建表时,设置自动增长的其实值及每次增量
2
--语句建表时设置自增列,从1开始增长,每次增加1
create
table
test(col1
int
indentity(1,1,))
3
--修改列为从1开始增长,每次增加10
alter
table
test
alter
col1
int
indentity(1,10)
1、打开数据库客户端,点击连接上你的数据库。
2、在对应的库上,点击展开表视图。
3、右键点击要设置的表,点击‘表设计’。
4、打开表设计页面,点击选中主键字段。
5、点击后,在下方就会出现这个字段的设置,点击勾选上‘Auto Increment’就行了,这个就是自增长的属性。
6、然后就完成了、
如果该字段不是主键,需要先设置该字段为主键:
alter table 表名 add primary key(字段名);
修改字段为自动增长
alter table 表名 change 字段名 字段名 字段类型 auto_increment;
select 自增列=identity(int,1,1), into #tb from tableName
drop table tabelNameselect into tableName from #tbdrop table #tb 其实可以直接在数据库中修改表的结构,增加一列(就是内容递增的那列),把这列设为标识列,自动递增1。保存一下就行了。
在sql2000中可以这样,不过感觉不怎么好如果表中关系多了,不建议这样用if exists (select from dbosysobjects where id = object_id(N'[dbo][p_setid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo][p_setid]
GO
--将表中的某个字段转换成标识字段,并保留原来的值
--注意,因为要删除原表,所以,如果表和其他表的关联,这些关联要重新创建
--调用示例
exec p_setid '表名','要转换的字段名'
--/
CREATE PROC P_SETID
@tbname sysname, --要处理的表名
@fdname sysname --要转换为标识字段的字段名
as
declare @s1 varchar(8000),@s2 varchar(8000),@tmptb sysname
select @s1='',@s2='',@tmptb='[tmp_'+@tbname+'_bak]'
select @s1=@s1+',['+name+']'
+case name when @fdname then '=identity(bigint,1,1)' else '' end
,@s2=@s2+',['+name+']'
from syscolumns where object_id(@tbname)=id
select @s1=substring(@s1,2,8000),@s2=substring(@s2,2,8000)
exec('select top 0 '+@s1+' into '+@tmptb+' from ['+@tbname+']
set identity_insert '+@tmptb+' on
insert into '+@tmptb+'('+@s2+') select '+@s2+' from ['+@tbname+']
set identity_insert '+@tmptb+' off
')
exec('drop table ['+@tbname+']')
exec sp_rename @tmptb,@tbname
go
--使用测试
--创建测试的表
create table 表(编号 bigint,姓名 varchar(10))
insert into 表
select 1,'张三'
union all select 2,'李四'
union all select 4,'王五'
go
--调用存储过程,将编号字段改为标识字段
exec p_setid '表','编号'
go
--显示处理结果
select from 表
--显示是否修改成功
select name from syscolumns
where object_id('表')=id and status=0x80
go
--删除测试
drop table 表
以上就是关于在SqlServer中怎样设置自动增长字段全部的内容,包括:在SqlServer中怎样设置自动增长字段、SQ数据库中怎样设置自增主键、SQL语句,如何修改一个表的一个字段为自动增长列等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)