1

I am working with the R programming language.

I have the following tables stored on a server : "my_table1", "my_table2", "my_table3", "my_table4", "my_table5"

I am trying to write a LOOP that performs SQL statements on these tables. As an example:

library(odbc)
library(DBI)

names = c("my_table1", "my_table2", "my_table3", "my_table4", "my_table5")
limits = abs(as.integer(rnorm(5,100,100)))

mycon = dbConnect(...)

results = list()

for (i in 1:length(names))

{

file_i = dbGetQuery(mycon, "select * from names[i] limit limits[i]")
results[[i]] = file_i

}

final_results <- do.call(rbind.data.frame, results)

But I don't think the dbgetquery() statement is able to recognize the SQL in this format.

Can someone please show me how to fix this?

Thanks!

1

2 Answers 2

1

to create the sql statement you have to use

paste("select * from ",names[i]," limit ",limits[i]) 

instead of

"select * from names[i] limit limits[i]"
Sign up to request clarification or add additional context in comments.

8 Comments

@ celimi: thank you so much! Can you please show me how I would use this?
file_i = dbGetQuery(mycon, paste("select * from ",names[i]," limit ",limits[i]) )
is this correct?
Yes, this should work.
Though this method is very prone to SQL injection problems and any names that may have characters that could interfere with the SQL syntax. It's much safer to use something like sqlInterpolate to correctly build SQL statements.
|
1

No need for an explicit for loop, we can do it with

results <-
  Map(function(nm, lim) dbGetQuery(mycon, paste("select * from", nm, "limit", lim)),
      dbQuoteIdentifier(mycon, names), limits)

Alternatively, generating the queries up front then lapplying over them:

queries <- paste("select * from", dbQuoteIdentifier(mycon, names), "limit", limits)
results <- lapply(queries, dbGetQuery, conn = mycon)

Comments

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.