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

4

23

Is there any way to pass a variable defined within R to the sqlQuery function within the RODBC package?

Specifically, I need to pass such a variable to either a scalar/table-valued function, a stored procedure, and/or perhaps the WHERE clause of a SELECT statement.

For example, let:

x <- 1 ## user-defined

Then,

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

Or...

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

Or...

example3 <- sqlQuery(myDB,"EXEC dbo.my_stored_proc (x)")

Obviously, none of these work, but I'm thinking that there's something that enables this sort of functionality.

Stupor answered 1/12, 2010 at 23:8 Comment(1)
A
22

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.

Archidiaconal answered 1/12, 2010 at 23:16 Comment(2)
Keep in mind, though, the dire consequences if your x value is something like col); DELETE * FROM my_table_fn; SELECT * FROM my_table_fn (col. Which is why it's much better to use placeholders than paste(). Some drivers support placeholders, some don't.Eolande
expanding (maybe improving) on @Dirk's answer, you can use sprintf() to build your string, I find it much easier to read than a paste(), e.g. example <- sqlQuery(myDB, sprintf("SELECT * FROM dbo.my_table_fn (%s)", x)). For one-variable substitutions, the difference between sprintf() and paste() is not a big deal, but for multiple-variable substitutions, it becomes more important, e.g. sqlQuery(myDB, sprintf("SELECT * FROM orders WHERE order_date >= '%s' AND order_date < '%s' AND customer_id = %s", start.date, end.date, customer.id))Blanka
G
3

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!

Greyhound answered 28/3, 2013 at 14:23 Comment(0)
S
-2

try with this

x <- 1
example2 <- fn$sqlQuery(myDB,"SELECT * FROM dbo.some_random_table AS foo WHERE foo.ID = '$x'")
Sager answered 23/12, 2010 at 5:3 Comment(2)
Error: object 'fn' not foundHonig
I suspect it's using gsubfn.Gorblimey
M
-2

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)
Meanie answered 8/2, 2016 at 21:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.