Pass R variable to RODBC's sqlQuery with multiple entries?

后端 未结 2 1210
萌比男神i
萌比男神i 2020-12-06 22:38

I\'m in the process of learning R, to wave SAS goodbye, I\'m still new to this and I somehow have difficulties finding exactly what I\'m looking for.

But for this sp

相关标签:
2条回答
  • 2020-12-06 23:17

    Assuming b looks like this:

    b <- data.frame(Noinscr=c("8535735", "8449336"))
    

    Then you only need a couple steps:

    # in case Noinscr is a factor
    b$Noinscr <- as.character(b$Noinscr)
    # convert the vector into a single string
    # NOTE that I subset to get the vector, since b is a data.frame
    B <- paste(b$Noinscr, collapse=",")
    # create your query
    paste("insert into TestTable (UniqueID) Values (",B,")", sep="")
    # [1] "insert into TestTable (UniqueID) Values (8535735,8449336)"
    

    You got odd results because sqlQuery returns a data.frame, not a vector. As you learned, using paste on a data.frame (or any list) can provide weird results because paste must return a character vector.

    0 讨论(0)
  • 2020-12-06 23:30

    Look into the collapse argument in the paste() documentation. Try replacing b with paste(b, collapse = ", "), as shown below.

    Edit As Joshua points out, sqlQuery returns a data.frame, not a vector. So, instead of paste(b, collapse = ", "), you could use paste(b[[1]], collapse = ", ").

    library(RODBC)
    channel <- odbcConnect("test")
    b <- sqlQuery(channel,
      "select top 1 Noinscr
       FROM table
       where PrixVente > 100
       order by datevente desc")
    
    sqlQuery(channel,
       ## note paste(b[[1]], collapse = ", ") in line below
       paste("insert into TestTable (UniqueID) Values (", paste(b[[1]], collapse = ", "),")", sep = "")
    
    0 讨论(0)
提交回复
热议问题