select [id],cast('' as varchar(50)) as address,[name],sex into newtable from oldtable
go
drop table oldtable
go
EXECUTE SP_RENAME N'DBO.newtable', N'oldtable', 'OBJECT'
go
--开启系统表写功能,不然无法创建存储过程
exec sp_configure 'allow updates',1 reconfigure with override
go
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_addfield]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_addfield]
GO
/*--在指定位置添加字段
添加字段到表中的指定位置
注意,字段定义必须符合 alter table add ...的规定
插入的位置从0开始,到字段数目-1结束
如果超过这个范围,则在表的尾部添加字段
一次只能添加一个字段,和 alter table 的限制完全一样
--删除测试
drop table tb
--*/
create proc p_addfield
@tbname sysname,
@fd_define nvarchar(1000), --字段定义(必须是合法的字段定义)
@colid int=-1 --添加位置:0--fieldcount-1,0表示在第一个字段前插入,-1或效的colid表示插入在最后
as
declare @s nvarchar(4000)
if isnull(objectproperty(object_id(@tbname),'IsUserTable'),0)=0
begin
select 错误='无效的表名'
return
end
--添加字段
set @s='alter table ['+replace(@tbname,']',']]')+'] add '+@fd_define
exec(@s)
--如果是添加在所有字段的未尾,则直接返回即可
if not exists(select 1 from syscolumns where id=object_id(@tbname) and colid between 1 and @colid+1)
return
--开启系统表写开关
exec sp_configure 'allow updates',1 reconfigure with override
set xact_abort on
begin tran
update syscolumns set colid=colid+1
where id=object_id(@tbname)
and colid>@colid
update syscolumns set colid=@colid+1
where id=object_id(@tbname)
and colid=(
select max(colid) from syscolumns
where id=object_id(@tbname))
commit tran
--关闭系统表写开关
exec sp_configure 'allow updates',0 reconfigure with override
go
--关闭系统表写功能
exec sp_configure 'allow updates',0 reconfigure with override
go
--我的想法是先用SELECT INTO 生成你想要的表,然后删除原表,然后重新命名新表为原表名
select [id],'' as address,[name],sex into newtable from oldtable
go
drop table oldtable
go
EXECUTE SP_RENAME N'DBO.newtable', N'oldtable', 'OBJECT'
go