Pass R variable to RODBC's sqlQuery? [duplicate]

廉价感情. 提交于 2019-11-26 17:36:30

Build the string you intend to pass. So instead of

example <- sqlQuery(myDB,"SELECT * FROM dbo.my_table_fn (x)")

do

example <- sqlQuery(myDB, paste("SELECT * FROM dbo.my_table_fn (", 
                                x, ")", sep=""))

which will fill in the value of x.

jonsedar

If you use sprintf, you can very easily build the query string using variable substitution. For extra ease-of-use, if you pre-parse that query string (I'm using stringr) you can write it over multiple lines in your code.

e.g.

q1 <- sprintf("
               SELECT basketid, count(%s)
               FROM %s
               GROUP BY basketid
              "
              ,item_barcode
              ,dbo.sales
              )
q1 <- str_replace_all(str_replace_all(q1,"\n",""),"\\s+"," ")
df <- sqlQuery(shopping_database, q1)

Side-note and hat-tip to another R chap

Recently I found I wanted to make the variable substitution even simpler by using something like Python's string.format() function, which lets you reuse and reorder variables within the string

e.g.

$: w = "He{0}{0}{1} W{1}r{0}d".format("l","o")
$: print(w)
"Hello World"

However, this function doesn't appear to exist in R, so I asked around on Twitter, and a very helpful chap @kevin_ushey replied with his own custom function to be used in R. Check it out!

patricio

try with this

x <- 1
example2 <- fn$sqlQuery(myDB,"SELECT * FROM dbo.some_random_table AS foo WHERE foo.ID = '$x'")
RIOT

With more variables do this:

  aaa <- "
      SELECT   ColOne, ColTwo 

FROM    TheTable 

 WHERE  HpId =  AAAA            and

  VariableId = BBBB     and 

  convert (date,date )  < 'CCCC'
  "


--------------------------

  aaa <- gsub ("AAAA",  toString(111),aaa)

  aaa <- gsub ("BBBB",  toString(2222),aaa)

  aaa <- gsub ("CCCC",  toString (2016-01-01) ,aaa)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!