Is there a better way to code this sqlQuery in R?

10,213

Solution 1

I would use something like this:

stsample<-sqlQuery(odcon,
    paste("
####DATASET CONSTRUCTION QUERY #########
    select 
    *  
    from 
    BOB.DESIGNSAMPLE T1, 
    BOB.DESIGNSUBJECTGROUP T2, 
    BOB.DESIGNEVENT T3, 
    BOB.CONFIGSAMPLETYPES T4 
    WHERE 
    T1.SUBJECTGROUPID = T2.SUBJECTGROUPID 
    AND T1.TREATMENTEVENTID = T3.TREATMENTEVENTID 
    AND T1.SAMPLETYPEKEY = T4.SAMPLETYPEKEY 
    AND T1.STUDYID = T2.STUDYID 
    AND T1.STUDYID = T3.STUDYID 
    AND T1.STUDYID = 
###################################   
    ", as.character(chstudid), sep="")
    )

Solution 2

What about using gsub("\n", " ", "long multiline select string") instead of paste?

Share:
10,213
PaulHurleyuk
Author by

PaulHurleyuk

Whew, About me ? In this itty bitty box ? That's a tough one ! Let's see, Full time Husband and Dad to an Awesome and fabulous wife and two cool young daughters. Part time computer geek. On the geek side I'm currently obsessing about R, Sweave, Latex, Kubuntu, MythTV, Photography, Gimp, DigiKam among other things....

Updated on June 13, 2022

Comments

  • PaulHurleyuk
    PaulHurleyuk almost 2 years

    I'm writing an R script to get some database data and then do stuff with it, using the RODBC package. Currently all my sqlQuery commands are one long string;

    stsample<-sqlQuery(odcon, paste"select * from bob.DESIGNSAMPLE T1, bob.DESIGNSUBJECTGROUP T2, bob.DESIGNEVENT T3, bob.CONFIGSAMPLETYPES T4 WHERE T1.SUBJECTGROUPID = T2.SUBJECTGROUPID AND T1.TREATMENTEVENTID = T3.TREATMENTEVENTID AND T1.SAMPLETYPEKEY = T4.SAMPLETYPEKEY AND T1.STUDYID = T2.STUDYID AND T1.STUDYID = T3.STUDYID AND T1.STUDYID = ", chstudid, sep=""))
    head(stsample)
    

    which looks ugly and is hard to read/update. I've tried putting them multiline, but then new line characters get in the way, currently my best is this using lots of paste's;

    stsample<-sqlQuery(odcon,
        paste(
            "select ",
                "* ", 
            "from ", 
                "BOB.DESIGNSAMPLE T1, ",
                "BOB.DESIGNSUBJECTGROUP T2, ",
                "BOB.DESIGNEVENT T3, ",
                "BOB.CONFIGSAMPLETYPES T4 ",
            "WHERE ",
                "T1.SUBJECTGROUPID = T2.SUBJECTGROUPID ",
                "AND T1.TREATMENTEVENTID = T3.TREATMENTEVENTID ",
                "AND T1.SAMPLETYPEKEY = T4.SAMPLETYPEKEY ",
                "AND T1.STUDYID = T2.STUDYID ",
                "AND T1.STUDYID = T3.STUDYID ",
                "AND T1.STUDYID = ",chstudid,
            sep="")
        )
    head(stsample)
    

    But I don't like having to put quotes around everyline, and getting my whitespace correct. Is there a better way ?