2

I would like to use a string of character IDs in the WHERE clause of SQL query. My id object looks like this

ids
 [1] "0000000000000000010000001" "0000000000000000010000002" "0000000000000000010000003"
 [4] "0000000000000000010000004" "0000000000000000010000005" "0000000000000000010000006"
 [7] "0000000000000000010000007" "0000000000000000010000008" "0000000000000000010000009"
[10] "0000000000000000010000010"

I would like to insert that object into this SQL query:

student <- sqlQuery(con,
  "select
    FSAS.a_id,
    FSAS.grade,
    FSAS.score,
    FSAS.placement,
    FSAS.start,
    FSAS.completion

    FROM db.Fact AS FSAS
      WHERE FSAS.a_id IN ids"

)

I think the entire SQL query has to be a string but I can't figure out how to get it right.

0

2 Answers 2

4

We can use paste to create the expression

expr1 <- sprintf("select
 FSAS.a_id,
 FSAS.grade,
 FSAS.score,
 FSAS.placement,
 FSAS.start,
 FSAS.completion 
 FROM db.Fact AS FSAS
   WHERE FSAS.a_id IN (%s)", paste0(sQuote(ids, q = FALSE), collapse=", "))

sqlQuery(con, expr1)
Sign up to request clarification or add additional context in comments.

2 Comments

Why do you load sqldf?
@r2evans While reading I somehow had a mental image of sqldf instead of sqlQuery. Thanks for correcting that
0

This should work:

qry = paste("select
    FSAS.a_id,
    FSAS.grade,
    FSAS.score,
    FSAS.placement,
    FSAS.start,
    FSAS.completion

    FROM db.Fact AS FSAS
      WHERE FSAS.a_id IN", ids, sep = "")

student <- sqlQuery(con,
     qry
)

2 Comments

Nooooo! (xkcd.com/327) Please don't suggest this as a viable solution, it will break in horrible ways when ids is not perfectly compliant.
qry will be a character vector, the length of ids. Essentially reproducing the query, over and over. And none of those queries will be valid anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.