解析若何用SQL語句在指定字段後面拔出新的字段。本站提示廣大學習愛好者:(解析若何用SQL語句在指定字段後面拔出新的字段)文章只能為提供參考,不一定能成為您想要的結果。以下是解析若何用SQL語句在指定字段後面拔出新的字段正文
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)。