R RODBC putting list of numbers into an IN() statement

ぐ巨炮叔叔 提交于 2019-12-04 08:38:52

You're not pasteing your query together correctly.

If you run the paste statement in isolation, you'll see that you get a vector of length 5000, so sqlQuery is only executing the first one of those, corresponding to the first element in samRowNum.

What you want to do is something more like this:

paste("select * FROM db where row_id in (", 
    paste(sampRowNum,collapse = ","),")", sep="")

Just as an added note (and since I've had to do stuff like this a lot...) constructing sql queries with an IN clause with strings is a bit more of a nuisance, since you have to tack on all the single quotes:

vec <- letters[1:5]

paste("SELECT * FROM db WHERE col IN ('",
    paste(vec,collapse = "','"),"')",sep = "")

[1] "SELECT * FROM db WHERE col IN ('a','b','c','d','e')"

If you do this a lot, you'll end up writing a little function that does that pasting of character vectors for you.

As always, this kind of SQL string manipulation is Not Good if you are dealing with user inputs (e.g. in a web app), due to SQL injection attacks. In my particular situation this isn't much of a concern, but in general people will prefer parametrized queries if you don't have much control over the input values.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!