--开启系统表写开关
exec sp_configure 'allow updates',1 reconfigure with override
go
/*--在指定位置添加字段
添加字段到表中的指定位置
注意,字段定义必须符合 alter table add ...的规定
如果超过这个范围,则在表的尾部添加字段
一次只能添加一个字段,和 alter table 的限制完全一样
--使用示例
exec p_addfield 'tb','field1 varchar(20)','field2'
--*/
CREATE proc p_addfield
@tbname sysname,--表名
@fd_define nvarchar(1000), --字段定义(必须是合法的字段定义)
@Ins_fd nvarchar(30) --被插入字段將放在Ins_fd字段前面
as
declare @s nvarchar(4000),@colid int
if not Exists(select 1 from sysobjects where name=@tbname and xtype='U')--isnull(objectproperty(object_id(@tbname),'IsUserTable'),0)=0
begin
print (@tbname+'表不存在,請核實')
return
end
IF not Exists(select 1 from syscolumns where id=object_id(@tbname) and name=@Ins_fd)
begin
print (@tbname+'不存在'+@Ins_fd+'字段,請核實')
return
End
--开启系统表写开关
exec sp_configure 'allow updates',1 reconfigure with override
set xact_abort on
begin tran
--添加字段
select @colid=(select colid from syscolumns where id=object_id(@tbname) and name=@Ins_fd)
set @s='alter table ['+replace(@tbname,']',']]')+'] add '+@fd_define
Exec (@s)
update syscolumns set colid=colid+1 where id=object_id(@tbname) and colid>=@colid
update syscolumns set colid=@colid where id=object_id(@tbname)
and colid=(select max(colid) from syscolumns where id=object_id(@tbname))
commit tran
if @@error=0
print ('字段插入成功')
Else
print ('字段插入失敗')
--开启系统表写开关
exec sp_configure 'allow updates',0 reconfigure with override
go
--开启系统表写开关
exec sp_configure 'allow updates',0 reconfigure with override
go