如何捕获从存储过程调用返回的多个表?
conn<- odbcDriverConnect('driver={SQL Server};server=server;database=db;trusted_connection=yes')
data <- sqlQuery(conn,paste("exec dbo.GetTest"),errors=FALSE)
它只捕获列表中返回的第一个表。
答案 0 :(得分:1)
RODBC可能没有从存储过程中检索多个记录集的功能。但是,Windows ADO确实具有NextRecordSet()方法。考虑让R使用RDCOMClient
库对ADO进行COM接口调用(当然假设您使用R for Windows)。在ADO的连接对象中,您传递与在RODBC中相同的连接字符串。
下面使用ADO&#39; GetRows()检索查询结果,返回在R中翻译为嵌套列表的二维数组。
SQL Server (存储过程)
CREATE PROCEDURE MultipleResults
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM Table1;
SELECT * FROM Table2;
END
R (ADO致电)
library(RDCOMClient)
conn <- COMCreate("ADODB.Connection")
rst <- COMCreate("ADODB.Recordset")
conn$Open("driver={SQL Server};server=server;database=db;trusted_connection=yes;")
# FIRST QUERY RESULT
rst$Open("MultipleResults", conn)
dfList1 <- rst$GetRows()
# RETRIEVE COLUMN NAMES
dfnames1 <- vapply(c(0:(rst[['Fields']]$Count()-1)),
function(i) (rst$Fields(i)$Name()), character(1))
# SECOND QUERY RESULT
rst <- rst$NextRecordset()
dfList2 <- rst$GetRows()
# RETRIEVE COLUMN NAMES
dfnames2 <- vapply(c(0:(rst[['Fields']]$Count()-1)),
function(i) (rst$Fields(i)$Name()), character(1))
# CLOSE OBJECTS
rst$Close(); conn$Close()
# FREE RESOURCES
rst <- conn <- NULL
rm(rst, conn)
gc()
# CONVERT NESTED LISTS TO DATAFRAMES
dfList1 <- lapply(dfList1, function(x) setNames(data.frame(x), dfnames1))
df1 <- do.call(rbind, dfList1)
dfList2 <- lapply(dfList2, function(x) setNames(data.frame(x), dfnames2))
df2 <- do.call(rbind, dfList2)