求一sql语句:在一数据库中同时对所有表增加一个相同的字段,该如何写这sql语句

什么都没留下 2013-01-25 10:01:28
求一sql语句:在一数据库中同时对所有表增加一个相同的字段,该如何写这sql语句。请各位大人帮帮忙。
...全文
227 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
我腫了 2013-01-25
  • 打赏
  • 举报
回复
USE test
GO



DECLARE @sql NVARCHAR(MAX)

Select @sql=ISNULL(@sql+NCHAR(13)+NCHAR(10),'')+'Alter table '+QUOTENAME(name)+' Add test_col nvarchar(50) Null' from sys.sysobjects Where type='U'

Exec (@sql)
/*
Print :
Alter table PayList Add test_col nvarchar(50) Null
Alter table test_tbA Add test_col nvarchar(50) Null

Result :
命令已順利完成。
*/


SELECT * FROM PayList
/*
ID  test_col
--- ---------
1   NULL
2   NULL
*/
SELECT * FROM test_tbA
/*
ID  Val  Val2   test_col
--- ---- ------ --------
1   a    7      NULL
*/
szm341 2013-01-25
  • 打赏
  • 举报
回复
上面代码多了个@col变量,要去掉 如果你是2000的话,select name from sys.tables要换成 select name from sysobjects where xtype='U'
KevinLiu 2013-01-25
  • 打赏
  • 举报
回复
可以查询sys.tables批量生成语句然后修改。 select 'ALTER TABLE ' +NAME +' 更改COLUMN语句' from sys.tables
szm341 2013-01-25
  • 打赏
  • 举报
回复

declare @table nvarchar(50)
declare cursor1 cursor for
select name from sys.tables
open cursor1
fetch next from cursor1 into @table
while @@fetch_status=0
begin
exec('alter table '+@table+' add newcol int')
fetch next from cursor1 into @table,@col
end
close cursor1
deallocate cursor1

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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