R dbGetQuery with dynamic string

点点圈 提交于 2019-12-06 07:21:09

Since I believe R DBI drivers have not yet implemented multiple SQL statements support, dbGetQuery only returns first statement.

Hence, you need to iteratively run your sqlcmd for multiple SQL statements such as with lapply to return a list of dataframes, followed by an rbind call for single master dataframe:

Id <- c(34, 22, 86)
sqlcmd <- paste("select col1, col2 from DB where ItemId =", Id, sep="")

# LIST OF DATAFRAMES
df_list <- lapply(sqlcmd , function(x) dbGetQuery(conn, x)) 

# FINAL DATAFRAME
final_df <- do.call(rbind, df_list)

Alternatively, use a UNION or UNION ALL for one SQL statement.

Id <- c(34, 22, 86)
sqlcmd <- paste("select col1, col2 from DB where ItemId =", Id, sep="")

single_sql <- paste(sqlcmd, collapse = " UNION ")
final_df <- dbGetQuery(conn, single_sql)

Or still use OR:

single_sql <- paste("select col1, col2 from DB where ItemId =", 
                    paste(Id, collapse=" OR ItemId = "))

final_df <- dbGetQuery(conn, single_sql)

I would normally do this like this:

Id1 <- c(34, 22, 86)

Id2 <- paste(Id1, collapse = ", ")
sqlcmd <- paste("select col1, col2 from DB where ItemId in (", Id2, ")", sep="")
Df <- dbGetQuery(conn, sqlcmd)

However if you want to return a list of data frames for each id and run the query three times you could do:

sqlcmd <- paste("select col1, col2 from DB where ItemId in (", Id1, ")", sep="")    
dataList <- lapply(sqlcmd, function(x) dbGetQuery(conn, x)) 

This also works with parametrized queries:

library(RSQLite)
conn <- dbConnect(SQLite())
dbWriteTable(conn, "DB", data.frame(col1 = 1, col2 = 2, ItemId = 3))

Id <- c(34, 22, 86)
sqlcmd <- "select col1, col2 from DB where ItemId = ?"
Df <- dbGetQuery(conn, sqlcmd, params = list(Id))

Created on 2018-06-11 by the reprex package (v0.2.0).

Recent versions of DBI and RSQLite will return a data frame that contains the results from these queries concatenated.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!