将多行SQL查询导入单个字符串

Tom*_*ell 15 string statistics r file rgui

R中,如何将多行文本文件(包含SQL)的内容导入单个字符串?

sql.txt文件如下所示:

SELECT TOP 100 
 setpoint, 
 tph 
FROM rates
Run Code Online (Sandbox Code Playgroud)

我需要将该文本文件导入R字符串,使其看起来像这样:

> sqlString
[1] "SELECT TOP 100 setpoint, tph FROM rates"
Run Code Online (Sandbox Code Playgroud)

那就是我可以像这样把它送到RODBC

> library(RODBC)
> myconn<-odbcConnect("RPM")
> results<-sqlQuery(myconn,sqlString)
Run Code Online (Sandbox Code Playgroud)

我已经尝试了如下的readLines命令,但它没有给出RODBC需要的字符串格式.

> 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]"           
> 
Run Code Online (Sandbox Code Playgroud)

Dir*_*tel 17

多功能paste()命令可以使用参数执行此操作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"
Run Code Online (Sandbox Code Playgroud)

  • 如果你有任何`--`评论,这可能会查询你的查询,不是吗?我使用`paste(readLines('pathto/query.sql'),collapse ="\n")` (6认同)

cby*_*mar 8

下面是一个R函数,它读入多行SQL查询(来自文本文件)并将其转换为单行字符串.该功能删除格式和整行注释.

要使用它,运行代码来定义函数,单行字符串将是运行ONELINEQ("querytextfile.sql","〜/ path/to/thefile")的结果.

工作原理:内联评论详细说明了这一点; 它读取查询的每一行并删除(无需替换)写出查询的单行版本所需的任何内容(如问题中所要求的).结果是一个行列表,其中一些是空白的并被过滤掉; 最后一步是将此(未列出)列表粘贴在一起并返回单行.

#
# This set of functions allows us to read in formatted, commented SQL queries
# Comments must be entire-line comments, not on same line as SQL code, and begun with "--"
# The parsing function, to be applied to each line:
LINECLEAN <- function(x) {
  x = gsub("\t+", "", x, perl=TRUE); # remove all tabs
  x = gsub("^\\s+", "", x, perl=TRUE); # remove leading whitespace
  x = gsub("\\s+$", "", x, perl=TRUE); # remove trailing whitespace
  x = gsub("[ ]+", " ", x, perl=TRUE); # collapse multiple spaces to a single space
  x = gsub("^[--]+.*$", "", x, perl=TRUE); # destroy any comments
  return(x)
}
# PRETTYQUERY is the filename of your formatted query in quotes, eg "myquery.sql"
# DIRPATH is the path to that file, eg "~/Documents/queries"
ONELINEQ <- function(PRETTYQUERY,DIRPATH) { 
  A <- readLines(paste0(DIRPATH,"/",PRETTYQUERY)) # read in the query to a list of lines
  B <- lapply(A,LINECLEAN) # process each line
  C <- Filter(function(x) x != "",B) # remove blank and/or comment lines
  D <- paste(unlist(C),collapse=" ") # paste lines together into one-line string, spaces between.
  return(D)
}
# TODO: add eof newline automatically to remove warning
#############################################################################################
Run Code Online (Sandbox Code Playgroud)