4

我正在编写一个 R 脚本来获取一些数据库数据,然后使用 RODBC 包对其进行处理。目前我所有的 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)

但我不喜欢在每一行都加上引号,并让我的空格正确。有没有更好的办法 ?

4

3 回答 3

6

我会使用这样的东西:

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="")
    )
于 2010-02-25T12:18:29.790 回答
2

使用 gsub("\n", " ", "long multiline select string") 代替粘贴怎么样?

于 2010-02-25T15:21:47.017 回答
0

这是一个非常古老的问题,但认为这可能对某人有用。

我发现有用的一件事是GetoptLong包,它提供了 qq() 函数。我认为它受到 Perl 的启发,但本质上它提供了一种使用简单变量插值来处理多行字符串的方法。例如:

library(GetoptLong)

tableName <- "myTable"
id <- 42

sqlQuery(odcon, qq("
    SELECT * FROM @{tableName}
    WHERE id = @{id}
    LIMIT 1
")

显然,我应该提到通常的警告,如果您直接使用用户输入,这是一个坏主意,在这种情况下最好使用某种准备好的语句。

于 2019-07-02T09:51:29.160 回答