Viten
May 1, 2022, 2:45pm
1
Hello guys,
I would like to know your opinion,
I am trying to blend r and SQL. What I would like is to extract from a SQL Table (in an Oracle Server) filtering just the countries that I am interested to analyze provided by an R array.
Is this possible?
What is the best way to mix r variables with SQL queries
Here the example:
``{r}
Country_List <- c("Spain","Italy","France","Belgium")
``
``{sql, connection=con, output.var="Data"}
SELECT ID, Company,Country
FROM Data
WHERE Country IN Country_List
``
Thank you very much
Here is a nice walk around solution that uses glue::glue_sql()
to prepare the array to be passed to the SQL chunk as an R variable
I had the same problem today and I think I found a solution using glue_sql() from the {glue } .
To quote the glue_sql() help page:
If you place a * at the end of a glue expression the values will be collapsed with commas. This is useful for the SQL IN Operator for instance.
Now, this sounds useful indeed
[grafik]
And here is the rmarkdown code:
```{r}
library(DBI)
library(glue)
library(RSQLite)
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars, overwrite = TRUE)
cyl_int <- c(4L, 6L)
cyl_sql <- glue_sql("{cyl_int*}")
```
```{sql, connection=con}
SELECT * FROM mtcars
WHERE cyl IN (?cyl_sql)
LIMIT 3
```
1 Like
system
Closed
May 8, 2022, 3:30pm
3
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.