我找到了一种直接(更快)提取MS Sql表内容的方法。但我不知道如何使用需要参数的存储过程来执行此操作。是否可以直接提取存储过程的结果到Excel文件?我知道如何间接地(使用数据表)这样做,但它太慢了。非常感谢你。
PS:这是我用来做一些测试的方法。它适用于表,但我需要的是提取存储过程的结果:
Private Sub SqlToExcelTest2(ByVal excelFilePath As String, _
ByVal nonExistingSheetName As String, _
ByVal sqlServer As String, _
ByVal sqlDatabase As String, _
ByVal sqlUserName As String, _
ByVal sqlPassword As String, _
ByVal sqlTable As String)
Const excelConnStrTemplate As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=2"";"
Dim connStr As String = String.Format(excelConnStrTemplate, _
excelFilePath)
Const adoQueryTemplate As String = "SELECT * INTO {0} FROM [odbc;Driver={{SQL Server}};" & _
"Server={1};Database={2};UID={3};PWD={4}].[{5}] "
Dim query As String = String.Format(adoQueryTemplate, _
nonExistingSheetName, _
sqlServer, _
sqlDatabase, _
sqlUserName, _
sqlPassword, _
sqlTable)
Using oleConn As New OleDb.OleDbConnection(connStr), oleCmd As New OleDb.OleDbCommand(query, oleConn)
oleConn.Open()
oleCmd.ExecuteNonQuery()
oleConn.Close()
End Using
End Sub
答案 0 :(得分:1)
我现在没有Excel检查,但您可以尝试:
并查看生成的VBA代码。
如果您始终运行相同的查询(或几个不同的查询),那么使用启动时自动刷新创建一些此类数据源可能就是您所需要的
答案 1 :(得分:0)
Python是您的选择吗?
设计参数并返回结果集的设计存储过程:
create procedure usp_Temp @howmany tinyint
as
set nocount on
create table #tmp (ID int identity, Letter char(1), String varchar(50))
declare @i tinyint
set @i = 0
while @i < @howmany
begin
insert into #tmp (Letter, String) values('X', 'The quick brown fox...')
set @i = @i + 1
end
select * from #tmp
set nocount off
在Python中,您可以这样做:
import dbi
import odbc
import csv
conn_str = 'Driver={SQL Server};Server=MyServer;Database=MyDb;Uid=MyLogin;Pwd=MyPwd'
conn = odbc.odbc(conn_str)
curs = conn.cursor()
curs.execute('exec usp_temp @howmany = 15')
results = curs.fetchall()
curs.close()
conn.close()
writer = csv.writer(open('tmp.csv', 'wb'), delimiter = ',',
quoting = csv.QUOTE_MINIMAL)
for result in results: writer.writerow(result)
Excel应该能够毫无问题地打开该CSV文件。