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
  • 69
  • 2
  • 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

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,897
  • 6
  • 45
  • 65
3

You could try with paste:

func <- function(x){
  sqlQuery(dbhandle, paste('select attr from myTable where cond =', x))
}
LyzandeR
  • 37,047
  • 12
  • 77
  • 87
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
  • 46,417
  • 11
  • 121
  • 167
-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
  • 2,044
  • 1
  • 16
  • 32