Using package:DBI
, I need to:
- run a parametrized query with different parameters (i.e. a vector of parameters);
- get the results sets concatenated (i.e.
rbind
ed as per R terminology orunion
ed as per SQL terminology); - and get the resulting table in the database for further manipulation.
dbBind()
/dbGetquery()
fullfils requirements 1 and 2, but I then need to write the resulting data frame to the database using dbWriteTable()
, which is ineficient:
library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "iris", iris)
res <- dbGetQuery(con,
"select * from iris where Species = ?",
params = list(c("setosa", "versicolor")))
dbWriteTable(con, "mytable", res)
Conversely, dbExecute()
fulfils requirement 3, but I don't think it has the "rbind
feature". Of course, this throw an error because the table would get overwritten:
dbExecute(con,
"create table mytable as select * from iris where Species = ?",
params = list(c("setosa", "versicolor")))
What is the most efficient/recommended way of doing so?
Notes:
- I am not the DBA and can only access the database through R.
- My example is too trivial and could be achieved in a single query. My use case really requires a parametrized query to be run multiple times with different parameters.
- I have to use Oracle, but I am interested in a solution even if it don't works with Oracle.