RODBC Temporary Table Issue when connecting to MS SQL Server

耗尽温柔 提交于 2019-11-27 13:38:04

The RODBC driver seems to think that when SQL Server returns any count of rows that the entire statement is complete. So you need to set nocount on at the beginning of your statement or stored procedure that is called.

set nocount on

This allowed me to use a stored procedure that was using temporary table in R.

The problem appears to be in your SQL syntax, not anything inherent with R or the RODBC package. I'm fairly certain you need to separate your SQL statements with the go command to make sure that the first statement finished executing before the second, and the third, and so on. Alternatively, you could break them up into four different statements as I did below. This works on my machine:

library(RODBC)
ch <- odbcConnect("details")

qry1 <- "create table #temptable (test int)"
qry2 <- "insert into #temptable(test) values(2)"
qry3 <- "select * from #temptable"
qry4 <- "drop table #temptable"

sqlQuery(ch, qry1)
sqlQuery(ch, qry2)
doesItWork <- sqlQuery(ch, qry3)
sqlQuery(ch, qry4)

And the output

> doesItWork
  test
1    2

EDIT

Turning all of your queries into a list object and iterating through them could save you some coding in the future. For example:

queryList <- list(qry1, qry2, qry3, qry4)
sqlOutput <- lapply(queryList, function(x) sqlQuery(ch, x))

This will generate some extraneous output that you may not care about, but the results you are interested in can be pulled with sqlOutput[[3]] where 3 represents the query of interest.

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