kaneroy kaneroy - 14 days ago 5
R Question

How to connect database with R

I have a problem using sqlQuery to connect database with R.

library(RODBC)
res =sqlQuery(channel,
paste0("select pb.col1,pb.col2 from pb,
mp,fb,st
where fb.col10 in ('%s',input),
and fb.col20=mp.col30
and pb.col40=st.col50
and pb.col45=st.col60
and mp.col40=pb.col80 and
pb.col80=st.col90"),
believeNRows=F)


Here,
input=c("abc","def","wvy","etz")
, but the real input has more than 10,000 string elements.

Channel is already set up for connecting with the database.

It looks like there are some problems with where-clause but I do not know how to fix it.

Can anyone help me with this?

Answer

paste0 does not work the way you are using it. You would need to use:

sprintf("select pb.col1,pb.col2 
         from pb,mp,fb,st 
            where fb.col10 in %s 
            and fb.col20=mp.col30 
            and pb.col40=st.col50 
            and pb.col45=st.col60 
            and mp.col40=pb.col80 and 
            pb.col80=st.col90", input)

Next, the way you have this structured will result in the query argument being a vector. You should aim to have query be a single string.

You might be better off using RODBCext

library(RODBCext)
res =sqlExecute(channel,
              "select pb.col1,pb.col2 
               from pb,mp,fb,st 
               where fb.col10 in ?, 
                  and fb.col20=mp.col30 
                  and pb.col40=st.col50 
                  and pb.col45=st.col60 
                  and mp.col40=pb.col80 
                  and pb.col80=st.col90",
              data = list(c("abc", "def", "wvy", "etz")),
              fetch = TRUE,
              stringsAsFactors = FALSE)

Lastly, I'm not sure this query is valid SQL syntax. Maybe I'm mistaken, but I don't think you can list multiple tables in the FROM clause like you have here. If you need multiple tables, there should be some way of joining them.

FROM Table1 LEFT JOIN Table2 ON Table1.ID = Table2.Ref

EDIT: I just saw that your input has over 10,000 elements, which will make sqlExecute pretty slow. Are you sure a LIKE is the best way to query these data. If possible, I would recommend some other approach to isolating the data that you need.

Comments