如何在一表中按指定位置插入一个字段? 用SQL语句。

冰霜icefrost 2003-09-20 08:28:04
原来的表old_Table 有字段 A,B,C
新表 new_table改为 A,D,B,C 
注意是有顺序的呀,程序已经在工厂运行很长时间,而且原来程序中有很多地方用insert into select A,B,C from old_table,
所以新加字段要有顺序。
...全文
262 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
冰霜icefrost 2003-09-20
  • 打赏
  • 举报
回复
谢谢,已经成功,
给分
txlicenhe 2003-09-20
  • 打赏
  • 举报
回复
或者用

Select A,'' as D,B,C into #tmp from 表
Drop table 表
Select * into 表 from #tmp

不知是否能达到楼主要求
txlicenhe 2003-09-20
  • 打赏
  • 举报
回复

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)。

34,874

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧