3

I have the following function in R:

dbhandle <- odbcDriverConnect('driver={SQL Server};
                              server=myServer;database=myDB;
                              trusted_connection=true')
func <- function(x){
     sqlQuery(dbhandle, 'select attr from myTable where cond = x')
}

I want to know how to pass the x parameter to the where condition for the cond attribute. For example, I want to calculate func(10), then the query must be:

select attr from myTable where cond = 10
Richard
  • 59
  • 1
  • 10
  • 1
    Please properly define what you mean by *parameter* as there is a concept called SQL parameterization which the below majority of answers do not employ except for one for the RODBC package. – Parfait Oct 30 '17 at 17:04

4 Answers4

4

You could try with paste:

func <- function(x){
  sqlQuery(dbhandle, paste('select attr from myTable where cond =', x))
}
LyzandeR
  • 35,731
  • 12
  • 70
  • 82
3

when using RODBC, I prefer to use parameterized queries. This becomes more valuable when you are passing character strings, as this avoids SQL Injection.

library(RODBCext)

sqlExecute(dbhandle, 
           "select attr from myTable where cond = ?",
           data = list(cond = 10),
           fetch = TRUE,
           stringsAsFactors = FALSE)
Benjamin
  • 16,180
  • 5
  • 43
  • 62
1

I like the glue package for these things, though it's really the same as paste, just prettier :

library(glue)

func <- function(x){
     sqlQuery(dbhandle, glue('select attr from myTable where cond = {x}'))
} 
moodymudskipper
  • 42,696
  • 10
  • 102
  • 146
-2

In this simple case you could even use dplyr itself:

library(dplyr)

func <- function(x) {
     tbl(dbhandle, "myTable") %>%
       select(attr) %>%
       filter(cond == x) %>%
       collect()
}
amarchin
  • 1,974
  • 1
  • 13
  • 30