Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import multiline SQL query to single string

In R, how can I import the contents of a multiline text file (containing SQL) to a single string?

The sql.txt file looks like this:

SELECT TOP 100 
 setpoint, 
 tph 
FROM rates

I need to import that text file into an R string such that it looks like this:

> sqlString
[1] "SELECT TOP 100 setpoint, tph FROM rates"

That's so that I can feed it to the RODBC like this

> library(RODBC)
> myconn<-odbcConnect("RPM")
> results<-sqlQuery(myconn,sqlString)

I've tried the readLines command as follows but it doesn't give the string format that RODBC needs.

> filecon<-file("sql.txt","r")
> sqlString<-readLines(filecon, warn=FALSE)
> sqlString
[1] "SELECT TOP 100 "                              "\t[Reclaim Setpoint Mean (tph)] as setpoint, "
[3] "\t[Reclaim Rate Mean (tph)] as tphmean "       "FROM [Dampier_RC1P].[dbo].[Rates]"           
> 
like image 571
Tommy O'Dell Avatar asked Jan 05 '10 01:01

Tommy O'Dell


1 Answers

The versatile paste() command can do that with argument collapse="":

lines <- readLines("/tmp/sql.txt")
lines
[1] "SELECT TOP 100 " " setpoint, "     " tph "           "FROM rates"     

sqlcmd <- paste(lines, collapse="")
sqlcmd
[1] "SELECT TOP 100  setpoint,  tph FROM rates"
like image 106
Dirk Eddelbuettel Avatar answered Oct 06 '22 11:10

Dirk Eddelbuettel