2010-02-25 75 views
3

我正在編寫一個R腳本來獲取一些數據庫數據,然後使用RODBC軟件包進行一些操作。目前我所有的sqlQuery命令都是一個長字符串;有沒有更好的方式來編寫R中的這個sqlQuery?

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) 

它看起來很醜,很難讀/更新。我已經試過把它們放在多行中,但是隨後新的行字符會阻擋,目前我最好的是使用大量的粘貼;

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) 

但我不喜歡在everyline周圍加上引號,並且讓我的空白正確。有沒有更好的辦法 ?

+0

看看http://stackoverflow.com/questions/1630724/can-i-gracefully-include-formatted-sql-strings-in-an-r-script – Marek 2010-02-25 11:07:18

+1

這個問題和一個馬立克鏈接太暗示了新的生產線問題。我在下面的回答中使用了gd047使用的粘貼語法,並且沒有新的換行符問題。我在SQL Server和Oracle中都使用了這種語法。什麼數據庫讓你對新的行語法感到悲傷? – 2010-02-25 17:01:41

+0

由於換行符,我沒有任何錯誤,我只是對他們有一種不好的感覺,但也許這是我錯了......(數據庫是甲骨文,如果它很重要) – PaulHurleyuk 2010-02-25 17:50:28

回答

6

我會用這樣的:

關於使用GSUB
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="") 
    ) 
2

什麼( 「\ n」, 「」, 「長多選擇string」)而不糊?

相關問題