简体   繁体   English

使用RODBC进行长SQL查询

[英]Using RODBC with long SQL query

I have a long SQL query that generates an*5 matrix when executed. 我有一个很长的SQL查询,在执行时会生成一个* 5矩阵。 I would like to loop through this 5 times, changing the year from 2008 to 2013. This will produce 5 matrices, all with 5 columns but each with a different number of rows. 我想循环这5次,从2008年到2013年改变年份。这将产生5个矩阵,所有矩阵都有5列但每行都有不同的行数。 I would like to append each matrix onto each other into one big matrix. 我想将每个矩阵相互叠加成一个大矩阵。 I already know that the total number of rows in the big matrix should be 17526. 我已经知道大矩阵中的总行数应该是17526。

The current code is like this: 目前的代码是这样的:

library(RODBC)
conn = odbcConnect(dsn = "database name")

startyear=2008
endyear=2013  
results=data.frame(matrix(ncol = 5, nrow = 17526))

for (i in startyear:endyear) {
query = paste("
SQL CODE
")
results[i] = sqlQuery(conn, query) }

2 Questions: 2个问题:

  1. Is there a way to have the paste command not print in the console? 有没有办法让粘贴命令不能在控制台中打印? The SQL query is over 600 lines and takes a while to print. SQL查询超过600行,需要一段时间才能打印。
  2. Any guesses as to why the loop doesn't work, as constructed? 任何猜测为什么循环不起作用,如构造? If I do not loop but rather set i equal to some year it works. 如果我不循环,而是设置我等于某一年它的工作原理。

use rbind , do.call and lapply : 使用rbinddo.calllapply

  ret <- lapply(startyear:endyear, function(i) {
                  query = paste("
                            SQL CODE
                          ")
                  sqlQuery(conn, query)
                })
  final <- do.call(rbind, ret)

Or better yet: 或者更好的是:

final <- do.call(rbind(lapply(
            startyear:endyear, function(i)
                sqlQuery(conn, paste("
                                SQL CODE
                               "))
              )))

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

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