求教!如何在存储过程里循环库名为变量我有20个库从B01到 B20 然后要从每一个库里 写一个语句 写到 一个新的库  AA里例:
insert into aa.dbo.test
select 
'b01' as b01,

from b01.dbo.test insert into aa.dbo.test
select 
'b02' as b02

from b02.dbo.test .....如此类推。这样 一个语句我要写20次。。  要是这种有20个 那就要写400次。求教如何用循环将这种写法。把库名写成变量来循环。

解决方案 »

  1.   


    declare @i int
    declare @sql varchar(4000)
    set @i = 1while @i <= 20
    begin
    select @sql = isnull(@sql,'') + ' insert into aa.dbo.test select ''b' + rigth(100+@i,2) + ''' as b' 
    + rigth(100+@i,2) + ' ,* from [b' + rigth(100+@i,2) + '].dbo.test '
    set @i = @i + 1
    endexec(@sql)--按楼主的意思写的,不过有个疑问,aa库中的test表有那么多列么? b01 b02 b03 b04 
    --而且插入的时候不选择aa库那个表的具体列
      

  2.   


    declare @i int
    declare @sql varchar(4000)
    set @i = 1while @i <= 20
    begin
    select @sql = isnull(@sql,'') + ' insert into aa.dbo.test select ''b' + rigth(100+@i,2) + ''' as 表的第一个列名' 
     + ' ,* from [b' + rigth(100+@i,2) + '].dbo.test '
    set @i = @i + 1
    endexec(@sql)
      

  3.   

    感谢大大赠教。已解决 把isnull(@sql,'') +  去掉就可以了。不然会重复
      

  4.   

    大大。出现个新问题。declare @imax int
    set @imax = select COUNT(id) as conid from gdjz.dbo.gdjz_code_t刚才的变量是写死的。我要用动态的取值 也就是循环的次数。
     这样写。。报错
    消息 156,级别 15,状态 1,第 5 行
    关键字 'select' 附近有语法错误。正解应该怎么写?
      

  5.   

    而且打算加入游标来做这个循环
    不然变量 的顺序会导致重复 。。
    有个CODE表 记录了 
    各库名所代表的代码
    B01   01  '4401'
    B02   02  '4402'
      

  6.   

    declare @imax int
    set @imax = COUNT(id) from gdjz.dbo.gdjz_code_t
      

  7.   

    declare MyCursor cursor
    for select [name] from [sysdatabases] 
     where name between 'B01' and 'B20'