Question

This seems ridiculous, but I just can't get this right - any help much appreciated please!

Basically: I'm using RMySQL to do some simple SQL, in order to get my head around how SQL works. I'd like to chain together a few SQL select queries, as a simple example. This is covered in the RMySQL PDF - but the example therein seems to be the incorrect syntax (http://cran.r-project.org/web/packages/RMySQL/RMySQL.pdf , page 3, example 6).

If I have three queries, say like this:

q1 <- "SELECT db.table FROM table WHERE stuff = 'blah' "
q2 <- "SELECT db.other_table FROM other_table WHERE stuff = 'different blah' "
q3 <- "SELECT db.table2 FROM table2 WHERE table2 = 1000"

and try to paste them as follows:

script <- paste(q1, q2, q3, sep=";")

the result is

> script
[1] "SELECT db.table FROM table WHERE stuff = 'blah' ;SELECT fb.other_table FROM
other_table WHERE stuff = 'different blah' ;SELECT db.table2 FROM table2 WHERE table2 =
'1000'

and so invoking dbSendQuery clearly fails.

I've tried \", but this also doesn't work:

q1 <- "SELECT db.table FROM table WHERE stuff = 'blah' \" "
q2 <- "SELECT db.other_table FROM other_table WHERE stuff = 'different blah' \""
q3 <- "SELECT db.table2 FROM table2 WHERE table2 = 1000 \" "

script <- paste(q1, q2, q3, sep=";")

> script
[1] "SELECT db.table FROM table WHERE stuff = 'blah' \" ;  ;SELECT db.other_table FROM
other_table WHERE stuff = 'different blah' \";SELECT db.table2 FROM table2 WHERE table2
= 1000 \" "

Can anyone please point out what I'm doing wrong?

EDIT: just for clarification, executing this via RMySQL as follows:

my.queries <- dbGetQuery(my.con, script, client.flag = CLIENT_MULTI_STATEMENTS)

as per the RMySQL manual, I get

RS-DBI driver: (could not run statement: You have an error in your SQL syntax;

Presumably, this is because the result of the paste function should be:

"SELECT db.table FROM table WHERE stuff = 'blah'" ;"SELECT fb.other_table FROM
other_table WHERE stuff = 'different blah'" ;"SELECT db.table2 FROM table2 WHERE table2
= '1000'"

Each of the individual queries works just fine, so I'm assuming that it's my paste command that's causing the issue.

EDIT: to simplify this: suppose I have two strings, as follows:

t1 <- "the 'stuff'"
t2 <- "more 'stuff'"
paste(t1, t2, sep=";")
[1] "the 'stuff' ; more 'stuff' "

what I'd like is for the result of the paste command to be "the 'stuff'";"more 'stuff'".

Was it helpful?

Solution

You have to pass the argument client.flag = CLIENT_MULTI_STATEMENTS to the function dbConnection, not to dgGetQuery.

Then, your first approach should work:

q1 <- "SELECT db.table FROM table WHERE stuff = 'blah' "
q2 <- "SELECT db.other_table FROM other_table WHERE stuff = 'different blah' "
q3 <- "SELECT db.table2 FROM table2 WHERE table2 = 1000"

script <- paste(q1, q2, q3, sep=";")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top