简体   繁体   English

如何使用EXCEL显示SQL Server 2005查询结果?

[英]How to use EXCEL to display SQL Server 2005 Query Result?

I have 50 databases in SQL Server 2005 and each database has the same table that I use to pull data from. 我在SQL Server 2005中有50个数据库,每个数据库都有用于提取数据的相同表。 I wrote SQL with cursor in it so that it loops through all the database specified. 我编写了带有游标的SQL,以便它遍历所有指定的数据库。 I got the result in the 50 different result panes. 我在50个不同的结果窗格中得到了结果。 My requirement is to import and display the results in 50 different sheets in the excel spreadsheet. 我的要求是在excel电子表格中将结果导入并显示在50个不同的工作表中。 My question: Is there a way in the excel that I can use so that I can display the results in 50 different sheets automatically? 我的问题:Excel中是否可以使用一种方法来自动将结果显示在50个不同的工作表中?

Thank you 谢谢

Yes. 是。 You can achieve this by using VBA. 您可以通过使用VBA来实现。 I'd record a macro where you import one of these tables into one (newly added) worksheet. 我记录了一个宏,您在其中将这些表之一导入一个(新添加的)工作表中。 You can then change this newly recorded macro to create all sheets and queries automatically. 然后,您可以更改此新记录的宏以自动创建所有工作表和查询。

Edit: To get started, you can read through the resources provided in the threads: How to get started with Visual Basic for Applications? 编辑:要开始,您可以阅读以下线程中提供的资源: 如何开始使用Visual Basic for Applications? or Where do I get started with VBA and macros programming in Word 2007? 在Word 2007中从哪里开始使用VBA和宏编程? (which actually also links to a video). (实际上也链接到视频)。

You can create temporary table 您可以创建临时表

create table #t (id int, col1 varchar, col2 varchar)

In your cursor you can insert data from 50 different databases into it 您可以在游标中插入来自50个不同数据库的数据

insert #t(id, col1, col2)
select id, col1, col2
from SomeDatabase.dbo.tt

And then select all data from it to one pane . 然后从其中选择所有数据 到一个窗格

select * from #t

Don't let data manipulate you. 不要让数据操纵您。 Manipulate it yourself :) 自己操作:)

I use the following script a lot to spew out MSSQL Data to an Excel sheet. 我经常使用以下脚本将MSSQL数据喷出到Excel工作表中。 Maybe this is what you are looking for. 也许这就是您想要的。

Sub ConnectSqlServer()

Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String

' Create the connection string.
sConnString = "Trusted_Connection=yes;Database=database;Server=sql;Driver={SQL Server}"

'conn.Open connString
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset

' Open the connection and execute.
'LOOP OVER SHEETS WITH DIFFERENT TABLES
conn.Open sConnString
For i = 1 To 50

Set rs = conn.Execute("SELECT * FROM TABLE")

' Check we have data.
If Not rs.EOF Then
    ' Transfer result.
    Sheets(i).Range("A2").CopyFromRecordset rs
' Close the recordset
    rs.Close
Else
    MsgBox "Error: No records returned.", vbCritical
End If
Next i
'END LOOP
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing

End Sub 结束子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM