create proc addcolumn
@tablename varchar(30), --表名
@colname varchar(30), --要加的列名
@coltype varchar(100), --要加的列類型
@colid int --加到第幾列
as
declare @colid_max int
declare @sql varchar(1000) --動態sql語句
--------------------------------------------------
if not exists(select 1 from sysobjects
where name = @tablename and xtype = 'u')
begin
raiserror 20001 '沒有這個表'
return -1
end
--------------------------------------------------
if exists(select 1 from syscolumns
where id = object_id(@tablename) and name = @colname)
begin
raiserror 20002 '這個表已經有這個列了!'
return -1
end
--------------------------------------------------
--保證該表的colid是連續的
select @colid_max = max(colid) from syscolumns where id=object_id(@tablename)
if @colid > @colid_max or @colid < 1
set @colid = @colid + 1
--------------------------------------------------
set @sql = 'alter table '+@tablename+' add '+@colname+' '+@coltype
exec(@sql)
select @colid_max = colid
from syscolumns where id = object_id(@tablename) and name = @colname
if @@rowcount <> 1
begin
raiserror 20003 '加一個新列不成功,請檢查你的列類型是否正確'
return -1
end
--------------------------------------------------
--打開修改系統表的開關
EXEC sp_configure 'allow updates',1 RECONFIGURE WITH OVERRIDE
--將新列列號暫置為-1
set @sql = 'update syscolumns
set colid = -1
where id = object_id('''+@tablename+''')
and colid = '+cast(@colid_max as varchar(10))
exec(@sql)
--將其他列的列號加1
set @sql = 'update syscolumns
set colid = colid + 1
where id = object_id('''+@tablename+''')
and colid >= '+cast(@colid as varchar(10))
exec(@sql)
--將新列列號復位
set @sql = 'update syscolumns
set colid = '+cast(@colid as varchar(10))+'
where id = object_id('''+@tablename+''')
and name = '''+@colname +''''
exec(@sql)
--------------------------------------------------
--關閉修改系統表的開關
EXEC sp_configure 'allow updates',0 RECONFIGURE WITH OVERRIDE
go
調用方法:
exec addcolumn '表名','新列名','新列類型',加到第幾個位置
如:
exec addcolumn 'test','id2','char(10)',2
表示將id2這個列加到表test的第二個位置,類型是char(10)。