Can I gracefully include formatted SQL strings in an R script?

前端 未结 5 1560
清歌不尽
清歌不尽 2020-12-14 04:55

I\'m working in an R script that uses a long SQL string, and I would like to keep the query relatively free of other markup so as to allow copying and pasting between editor

5条回答
  •  有刺的猬
    2020-12-14 05:40

    If you're an old C programmer from way back, as I am, you might enjoy just using sprintf().

    Borrowing Ian's example:

    y<-"y1"
    x<-"somethingorother"
    query <- sprintf(
    'SELECT DISTINCT x AS %s,
                     y AS %s,
     FROM tbl
     WHERE id=%%s
     AND num=%%d', x, y)
    

    yields:

    > cat(query,"\n")
    SELECT DISTINCT x AS somethingorother,
                     y AS y1,
     FROM tbl
     WHERE id=%s
     AND num=%d 
    

提交回复
热议问题