如何向SQL Server 2005 数据库DB的所有表中插入新的列A(首先判断A是不是已经存在),求考虑全面的语句 5
declare@countCreateTimeint,@countUpdateTimeint,@tabvarchar(100)DECLAREMy_CursorCURSOR...
declare @countCreateTime int ,@countUpdateTime int,@tab varchar(100)
DECLARE My_Cursor CURSOR --定义游标
FOR (Select TABLE_NAME FROM DB.INFORMATION_SCHEMA.TABLES Where TABLE_TYPE='BASE TABLE') --查出需要的集合放到游标中
OPEN My_Cursor; --打开游标
FETCH NEXT FROM My_Cursor INTO @tab; --读取第一行数据
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @tab;
select @countCreateTime=count(*) from syscolumns where id=object_id(@tab) and name='CreateTime'
select @countUpdateTime=count(*) from syscolumns where id=object_id(@tab) and name='UpdateTime'
if(@countCreateTime =0)
begin
print @tab
exec('alter table '+ @tab +' add CreateTime datetime')
end
if(@countUpdateTime =0)
begin
print @tab
exec('alter table '+ @tab + ' add UpdateTime datetime')
end
FETCH NEXT FROM My_Cursor INTO @tab; --读取下一行数据
END
CLOSE My_Cursor; --关闭游标
DEALLOCATE My_Cursor; --释放游标
GO
上面是我成功的,但数据库中有User表 展开
DECLARE My_Cursor CURSOR --定义游标
FOR (Select TABLE_NAME FROM DB.INFORMATION_SCHEMA.TABLES Where TABLE_TYPE='BASE TABLE') --查出需要的集合放到游标中
OPEN My_Cursor; --打开游标
FETCH NEXT FROM My_Cursor INTO @tab; --读取第一行数据
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @tab;
select @countCreateTime=count(*) from syscolumns where id=object_id(@tab) and name='CreateTime'
select @countUpdateTime=count(*) from syscolumns where id=object_id(@tab) and name='UpdateTime'
if(@countCreateTime =0)
begin
print @tab
exec('alter table '+ @tab +' add CreateTime datetime')
end
if(@countUpdateTime =0)
begin
print @tab
exec('alter table '+ @tab + ' add UpdateTime datetime')
end
FETCH NEXT FROM My_Cursor INTO @tab; --读取下一行数据
END
CLOSE My_Cursor; --关闭游标
DEALLOCATE My_Cursor; --释放游标
GO
上面是我成功的,但数据库中有User表 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询