I am reading list of values from CSV file in R, and trying to pass the values into IN condition of SQL(dbGetQuery). Can some one help me out with this?
library(r
The SQL code you pass in the second argument to dbGetQuery
is just a text string, hence you can construct this using paste
or equivalents.
You are after something like the following:
in_clause <- paste0("('", paste0(pii$PII_ID, collapse = "', '"), "')")
sql_text <- paste0("SELECT ARTICLE_ID
FROM JRBI_OWNER.JRBI_ARTICLE_DIM
WHERE PII_ID IN ", in_clause)
data <- dbGetQuery(jdbcConnection, sql_text)
However, the exact form of the first paste0
depends on the format of PII_ID
(I have assumed it is text) and how this format is represented in sql (I have assumed single quotes).
Be sure to check sql_text
is valid SQL before passing it to dbGetQuery
.
IMPORTANT: This approach is only suitable when pii
contains a small number of values (I recommend fewer than 10). If pii
contains a large number of values your query will be very large and will run very slowly. If you have many values in pii
then a better approach would be a join or semi-join as per @nicola's comment.