批量更改数据库表架构(生成sql后直接执行!)

批量更改数据库表架构(生成sql后直接执行!)
use my_test; --当前数据库
declare  @alltable varchar(1000),
         @SchemaOld varchar(1000),
         @SchemaNew varchar(1000),
         @NewSql VARCHAR(max),
         @Index INT;
SET @SchemaOld='dbo';--原架构名称
SET @SchemaNew='SC';--新架构名称
SET @NewSql='';
SET @Index=1;
SELECT @alltable=isnull(@alltable+',','')+[name] FROM SysObjects Where XType='U' ORDER BY Name;
declare @s varchar(1000),@ns varchar(1000);
set @s=@alltable;
set @s=@s+',';
while (charindex(',',@s)<>0)
begin
    select @ns=substring(@s,1,charindex(',',@s)-1);
    --执行操作 
    --SET  @NewSql=@NewSql+ 'alter SCHEMA '+@SchemaNew+'  transfer '+@SchemaOld+'.'+@ns+';' 
    PRINT '/*'+CAST(@Index AS varchar)+'*/ alter SCHEMA '+@SchemaNew+'  transfer '+@SchemaOld+'.'+@ns+';' ;
    SET @Index=@Index+1;
    --结束操作
set @s=stuff(@s,1,charindex(',',@s),'');
end

PRINT @NewSql;

 

posted @ 2014-12-30 16:00  xyzhuzhou  阅读(301)  评论(0编辑  收藏  举报