JMonroe JMonroe - 1 month ago 6
SQL Question

Writing Lengthy SQL queries via RODBC in R

I am researching how to read in data from a server directly to a data frame in R. In the past I have written SQL queries that were over 50 lines long (with all the selects and joins). Any advice on how to write long queries in R? Is there some way to write the query elsewhere in R, then paste it in to the "sqlQuery" part of the code?

Answer

Keep long SQL queries in .sql files and read them in using readLines + paste with collapse='\n'

my_query <- paste(readLines('your_query.sql'), collapse='\n')
results <- sqlQuery(con, my_query)
Comments