2010-01-05 29 views
15

In R, come è possibile importare il contenuto di un file di testo multilinea (contenente SQL) in una stringa singola?Importazione query SQL multilinea su stringa singola

Il file sql.txt assomiglia a questo:

SELECT TOP 100 
setpoint, 
tph 
FROM rates 

ho bisogno di importare il file di testo in una stringa R tale che assomiglia a questo:

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

che è così che posso alimentarlo al RODBC come questo

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

Ho provato il comando readLines come segue ma non gi ve il formato stringa richiesto da 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]"   
> 

risposta

17

Il versatile paste() comando può farlo con l'argomento 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" 
+1

Grazie Dirk, funziona, eccetto che la stringa è simile a "SELEZIONA TOP 100 \ t setpoint, \ t tph \ t FROM tariffe \ t". Ho solo bisogno di aggiungere gsub ("\ t", "", sqlcmd) –

+0

Beh, quello che ho copiato non aveva le schede, in ogni caso il parser SQL probabilmente ignorerebbe comunque le schede e hai trovato il 'gsub()' - tutto bene . –

+6

Questo probabilmente macellerà la tua query se hai qualche '--' commento, non è vero? Vorrei usare 'paste (readLines ('pathto/query.sql'), collapse =" \ n ")' –

1

provare paste(sqlString, collapse=" ")

4

Ecco la versione finale di quello che sto usando. Grazie Dirk.

fileconn<-file("sql.txt","r")   
sqlString<-readLines(fileconn)   
sqlString<-paste(sqlString,collapse="") 
gsub("\t","", sqlString) 
library(RODBC) 
sqlconn<-odbcConnect("RPM") 
results<-sqlQuery(sqlconn,sqlString) 
library(qcc) 
tph <- qcc(results$tphmean[1:50], type="xbar.one", ylim=c(4000,12000), std.dev=600) 
close(fileconn) 
close(sqlconn) 
0

Io uso sql <- gsub("\n","",sql) e sql <- gsub("\t","",sql) insieme.

8

Di seguito è riportata una funzione R che legge in una query SQL multilinea (da un file di testo) e la converte in una stringa a riga singola. La funzione rimuove la formattazione e i commenti su tutta la linea.

Per utilizzarlo, eseguire il codice per definire le funzioni e la stringa su una sola riga sarà il risultato dell'esecuzione di ONELINEQ ("querytextfile.sql", "~/percorso/per/il file").

Come funziona: i commenti incorporati dettagliano questo; legge ogni riga della query ed elimina (sostituisce con niente) tutto ciò che non è necessario per scrivere una versione a riga singola della query (come richiesto nella domanda). Il risultato è un elenco di righe, alcune delle quali sono vuote e vengono filtrate; l'ultimo passo è incollare insieme questo elenco (non in elenco) e restituire la singola riga.

#
# 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 
############################################################################################# 
+0

... Sai, questa è probabilmente la migliore risposta di auto-promozione che abbia mai visto. Potresti aggiungere una breve spiegazione di come funziona anche la tua risposta? (E con questo intendo [modifica la tua risposta] (http://stackoverflow.com/posts/30551944/edit)) –

2

Questo è quello che io uso:

# Set Filename 
fileName <- 'Input File.txt' 

doSub <- function(src, dest_var_name, src_pattern, dest_pattern) { 
    assign(
      x  = dest_var_name 
     , value = gsub(
          pattern  = src_pattern 
         , replacement = dest_pattern 
         , x = src 
        ) 
     , envir = .GlobalEnv 
    ) 
} 


# Read File Contents 
original_text <- readChar(fileName, file.info(fileName)$size) 

# Convert to UNIX line ending for ease of use 
doSub(src = original_text, dest_var_name = 'unix_text', src_pattern = '\r\n', dest_pattern = '\n') 

# Remove Block Comments 
doSub(src = unix_text, dest_var_name = 'wo_bc_text', src_pattern = '/\\*.*?\\*/', dest_pattern = '') 

# Remove Line Comments 
doSub(src = wo_bc_text, dest_var_name = 'wo_bc_lc_text', src_pattern = '--.*?\n', dest_pattern = '') 

# Remove Line Endings to get Flat Text 
doSub(src = wo_bc_lc_text, dest_var_name = 'flat_text', src_pattern = '\n', dest_pattern = ' ') 

# Remove Contiguous Spaces 
doSub(src = flat_text, dest_var_name = 'clean_flat_text', src_pattern = ' +', dest_pattern = ' ') 
1

E 'possibile utilizzare readChar() invece di readLines(). Ho avuto un problema con commenti misti (--10) e questo ha sempre funzionato bene per me.

sql <- readChar(path.to.file, file.size(path.to.file)) 
query <- sqlQuery(con, sql, stringsAsFactors = TRUE) 
Problemi correlati