Ray Kodiak
Ray Kodiak

Reputation: 89

R Import Multiple Tables from database using sqlQuery

I know how to import a table from the database, it works; but what if I have 6 tables, is there a better way to import from 6 different tables and create 6 different data.frames ?

Notes <- sqlQuery(dbConnection, " SELECT * FROM Table1")

??

Upvotes: 2

Views: 1630

Answers (1)

Parfait
Parfait

Reputation: 107567

Consider an lapply call across a list of tables:

tableList <- c("Table1","Table2","Table3","Table4","Table5","Table6")

# BUILD LIST OF DFS FROM QUERIES
dfList <- lapply(tableList, function(t) sqlQuery(dbConnection, paste0("SELECT * FROM ",  t))

# NAME EACH ELEMENT TO CORRESPONDIND TABLE NAME
dfList <- setNames(dfList, tableList)

And then if you want separate dataframes use list2env but you can always work directly from dfList to avoid many objects in global environment:

list2env(dfList, envir=.GlobalEnv)

Upvotes: 4

Related Questions