问题描述:
比如将 表a 的 b列修改为自增字段 b列本为 int类型 not null
我有表a 不是创建 是修改 不能删除B列 有外键约束,表a 现在还没有值
问题解答:
只可删除再新增..
alter table a drop constraint 外健约束--删除
select b=identity(int,1,1) --指定需要的列
into a1 from a
drop table a
exec sp_rename 'a1','a'
alter table a add constraint 外健约束--加上
=======================
那更简单了,我还以为你有数据呢..
先删除外键约束,然后删除B列,然后新增一个自增的B列,然后添加约束..
OK..
=======================
/*--将表中的某个字段转换成标识字段,并保留原来的值
注意,因为要删除原表,所以,如果表和其他表的关联,这些关联要重新创建
--邹建 2003.12--*/
/*--调用示例
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 表
sql server 中普通字段修改为自增字段时,如图:
把否修改为是:
按ctrl+S时报:
这时应:
去掉对勾
确定。
回到设计表中再次按ctrl+s保存字段自增。
alter table student
drop column b,--先得删除列
add b int identity(1,1) not null
go
alter table a alter column b int identity(1,1)
一句话搞定