简体   繁体   English

执行用R中的Excel单元格编写的SQL查询

[英]Executing SQL queries written in Excel Cells in R

I'm writing SQL queries in Excel Spreadsheets and I have linked Rstudio with SQL server using ODBC. 我正在Excel电子表格中编写SQL查询,并且已使用ODBC将Rstudio与SQL服务器链接。

Now, using sqlQuery command in R, any query can be run. 现在,在R中使用sqlQuery命令,可以运行任何查询。 For example, 例如,

library(RODBC) 
mycon <- odbcConnect("MYSQLSERVER") 
a1 <- sqlQuery(mycon,paste("SELECT TOP 10 * FROM USER"]

If the same query (or a number of queries) is written in a particular cell (or different cells) in an Excel file, how can I get the output? 如果在Excel文件的特定单元格(或不同单元格)中写入了相同的查询(或多个查询),如何获得输出?

Edit : The excel file will be used as an input and once all the queries are written in the excel file, the R code will be run. 编辑excel文件将用作输入,并且所有查询都写入excel文件后,R代码将运行。 The user will only be provided to edit the excel file. 仅向用户提供编辑excel文件的权限。 How do I connect all this process? 如何连接所有这些过程? I just need a start. 我只需要开始。 I found XLConnect and the readNamedRegion() function but that's the extent of it. 我找到了XLConnect和readNamedRegion()函数,但这就是它的范围。

With same exact package, RODBC, you can actually run SQL queries on Excel workbooks, even specifying a range of the needed cells. 使用相同的软件包RODBC,您实际上可以在Excel工作簿上运行SQL查询,甚至可以指定所需单元格的范围。

Consider connecting to Excel, retrieving SQL statements in cells into a dataframe and then looping through such a queriesdf to pass as calls to SQL Server fetches. 考虑连接到Excel,将单元格中的SQL语句检索到数据框中 ,然后遍历此类querydf以作为对SQL Server的调用的传递。

library(RODBC)

# EXCEL CONNECTION -----------------------------
xlconn <- odbcDriverConnect('Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};
                             DBQ=C:\\Path\\To\\ExcelWorkbook.xlsx')
# WHOLE WORKSHEET (FIRST ROW AS HEADERS)
queriesdf <- sqlQuery(xlconn, "SELECT * FROM [Sheet1$]")
# SPECIFIC RANGE (FIRST ROW AS HEADERS)
queriesdf <- sqlQuery(xlconn, "SELECT * FROM [Sheet1$A1:Z100]")
close(xlconn)

# SQL SERVER CONNECTION ------------------------
mssqlconn <- odbcConnect("MYSQLSERVER")     
# LIST OF DATA FRAMES
dfList <- lapply(queriesdf$QueryCol, function(q) sqlQuery(mssqlconn, q))
close(mssqlconn)

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

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