如何将游标的结果插入tempTable

时间:2016-02-22 16:00:42

标签: sql-server cursor temp-tables

我有大约60个我正在查询的具有相同表格的数据库;但是,我希望将查询结果插入到临时表中,以便我可以使用存储在该临时表中的结果创建格式良好的报告。 我如何实现这一目标? 下面是我的查询循环每个数据库并运行查询以选择所有活动订单:

DECLARE @db_name Varchar(100)

DECLARE @SQL Varchar(3000)

DECLARE c_db_names CURSOR FOR
SELECT name 
FROM master.dbo.sysdatabases
WHERE name NOT IN('master','AdventureWorks2008','TestDB','Development','Northwind') --might need to exclude more databases

OPEN c_db_names

FETCH c_db_names INTO @db_name

WHILE @@Fetch_Status = 0
BEGIN   

SET @SQL = 'SELECT OrderID, OrderStatus, OrderDetails, FulfillmentDate, ShippingDate , AddDate from 
       '+ @db_name +'.dbo.ActiveOrders inner join '+ @db_name +'.dbo.FinalShipmentNumbers on '+ @db_name +'.dbo.ActiveOrders.OrderDetails = 
       '+ @db_name +'.dbo.FinalShipmentNumbers.OrderID where addDate between ''1/30/2016'' and ''2/26/2016'''

SELECT @db_name As Client_Name
EXEC(@SQL)      
FETCH c_db_names INTO @db_name
END

CLOSE c_db_names
DEALLOCATE c_db_names

1 个答案:

答案 0 :(得分:1)

以下是这将是如何的基本语法。

SET @SQL = 'INSERT #YourTempTableHere (ColumnList)
SELECT OrderID, OrderStatus, OrderDetails, FulfillmentDate, ShippingDate , AddDate from 
       '+ @db_name +'.dbo.ActiveOrders inner join '+ @db_name +'.dbo.FinalShipmentNumbers on '+ @db_name +'.dbo.ActiveOrders.OrderDetails = 
       '+ @db_name +'.dbo.FinalShipmentNumbers.OrderID where addDate between ''1/30/2016'' and ''2/26/2016'''