SQL Server光标切断

时间:2016-02-18 19:02:41

标签: sql sql-server cursor

我目前正在整理一个脚本,该脚本将在SQL服务器中暂存一些数据,以便由另一个进程提取。然而,似乎光标im建筑正在切断。

例如,脚本应查看所有名称如TESTDB_的DB,但在脚本中途切断,并且在打印出来时,语句甚至不会完全生成。以下是该脚本的示例。

declare @sql varchar(8000), @envname varchar(10), @dbs varchar(100)
declare @db CURSOR
set @sql = ''
set @db = cursor for
    --dynamically get the current servers that are online
    select name from sys.databases where name like 'TESTDB_%'
open @db
fetch next from @db into @dbs
while @@fetch_status = 0
    begin
    set @sql=@sql+'
insert into DB1 (DBNAME,TEST1,TEST2,TEST3,TEST4,TEST5) 
select  DB_NAME() as ''DBNAME'', a.Test1, b.Test2, c.test3, d.test4, e.test5 
from ['+@dbs+'].[client].Table1 a 
    inner join ['+@dbs+'].[client].table2 b on a.ID=b.Id
    inner join ['+@dbs+'].[client].table3 c on c.ID=a.Id
    inner join ['+@dbs+'].[client].table4 d on d.ID=a.Id
    inner join ['+@dbs+'].[client].table5 e on e.ID=a.Id
'           
fetch next from @db into @dbs
    end
close @db
deallocate @db
print @sql 
set nocount off

1 个答案:

答案 0 :(得分:1)

试试这个:

SET NOCOUNT ON; 

declare @sql varchar(8000), @envname varchar(10), @dbs varchar(100)
declare @db CURSOR
set @sql = ''
set @db = cursor for
    --dynamically get the current servers that are online
    select name from sys.databases where name like 'TESTDB_%'
open @db
fetch next from @db into @dbs
while @@fetch_status = 0
    begin
    SELECT @sql+='
insert into DB1 (DBNAME,TEST1,TEST2,TEST3,TEST4,TEST5) 
select  DB_NAME() as ''DBNAME'', a.Test1, b.Test2, c.test3, d.test4, e.test5 
from ['+@dbs+'].[client].Table1 a 
    inner join ['+@dbs+'].[client].table2 b on a.ID=b.Id
    inner join ['+@dbs+'].[client].table3 c on c.ID=a.Id
    inner join ['+@dbs+'].[client].table4 d on d.ID=a.Id
    inner join ['+@dbs+'].[client].table5 e on e.ID=a.Id
'           
fetch next from @db into @dbs
    end
close @db
deallocate @db
print (@sql) 

结果:

enter image description here