sql cursor将结果插入表中

时间:2016-10-27 13:27:30

标签: sql-server cursor

我创建了一个游标,它遍历所有数据库并显示每个数据库的1条记录。

我希望将记录插入到我可以查看的1个表中。查询可能会更改,这就是为什么我不想为特定查询创建表结构并插入它。我想使用“select into”子句,但是第二次光标运行时会失败

DECLARE @DB_Name varchar(100) 
DECLARE @Command nvarchar(200)
DECLARE database_cursor CURSOR FOR SELECT name FROM #DBNAME

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0 
BEGIN 
     SELECT @Command = 'use [' + @DB_Name + '] Select '''+ @DB_Name + ''' ,'+

 --Enter query below
 '* from authentication where username like ''%clair@indicater%'' and password = ''Rohan2410'''

 --  print @Command
 EXEC sp_executesql @Command


 FETCH NEXT FROM database_cursor INTO @DB_Name 
END

CLOSE database_cursor 
DEALLOCATE database_cursor

1 个答案:

答案 0 :(得分:1)

你应该更好地使用INSERT INTO ...而不是SELECT INTO,如下所示:

DECLARE @DB_Name varchar(100) 
DECLARE @Command nvarchar(200)
DECLARE database_cursor CURSOR FOR SELECT name FROM #DBNAME

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0 
BEGIN

     SELECT @Command = 'use [' + @DB_Name + '] 

     IF OBJECT_ID(''tempdb..##output'') IS NULL
         BEGIN
            SELECT NULL AS DB_Name,* 
            INTO ##output
            FROM authentication WHERE 1=0
         END

     INSERT INTO ##output
     Select '''+ @DB_Name + ''' ,'+

 --Enter query below
 '* from authentication where username like ''%clair@indicater%'' and password = ''Rohan2410'''

 --  print @Command
 EXEC sp_executesql @Command


 FETCH NEXT FROM database_cursor INTO @DB_Name 
END

CLOSE database_cursor 
DEALLOCATE database_cursor

SELECT * FROM ##output

DROP TABLE ##output

基本上,在第一个游标迭代中,我们将创建一个具有正确结构的空临时表。然后我们只是插入临时表。