cowboy
cowboy

Reputation: 661

Output results of SQL in function to R dataframe

I have a working R function that queries a server database and returns results as expected, however it simply prints the result to the console and I want to store the result as a dataframe object.

I have tried the code below

params <- function(
  BEG = '201801',
  END = '201802') {


  con <- dbConnect(odbc::odbc(), dsn = DSN)

   data <- odbc::dbSendQuery(con,  " SELECT A BUNCH OF DATA 
                      FROM some_tables where everything is what I want")

  odbc::dbBind(data, list(BEG, END))
  odbc::dbFetch(data) -> test
  er_vists <- as.data.frame(return(test))
}

params()

Everything works just fine, I just cant figure out how to save results to dataframe. Does that need to happen outside of the function? Any help or link to possible solutions would be appreciated.

Upvotes: 0

Views: 255

Answers (1)

Cettt
Cettt

Reputation: 11981

Hi as far as I can see your function works correctly.

Just modify the last line in your function save the output to a variable like this:

params <- function(BEG = '201801', END = '201802') {

  con <- dbConnect(odbc::odbc(), dsn = DSN)

  data <- odbc::dbSendQuery(con,  " SELECT A BUNCH OF DATA 
                            FROM some_tables where everything is what I want")

  odbc::dbBind(data, list(BEG, END))
  odbc::dbFetch(data) -> test
  return(as.data.frame(test))
}

mydata <- params()
mydata


mydata <- params()

Upvotes: 3

Related Questions