与RODBCext和RODBC,使用R,以执行SQL存储过程(Using R with RODBCe

2019-10-23 10:13发布

我现在用的是RODBCext包和RODBC包。如果我用这个代码存储过程的工作原理来执行使用R.在SQL Server 2008的存储过程。

query <- "EXEC [dbo].[usp_SchoolMerge] @Number = ?, 
                                       @Name = ?, 
                                       @Type = ?, 
                                       @Comments = ?, 
                                       @DualEnrollment =?, 
                                       @CEP = ?, 
                                       @DistrictGuidId = ?,
                                       @ImportName = ?,
                                       @ImportID = ?"

query <- gsub("[[:space:]]+", " ", query)

con2 <- odbcConnect("database", uid="userid", pwd="password")

for(i in 1:nrow(us11_12_00_school)) {

  sqlExecute(con2, query, us11_12_00_school[i,])

}

odbcClose(con2)

如果我尝试使用量化的形式解释这里 2.3.2下使用参数化查询。

query <- "EXEC [dbo].[usp_SchoolMerge] @Number = ?, 
                                       @Name = ?, 
                                       @Type = ?, 
                                       @Comments = ?, 
                                       @DualEnrollment =?, 
                                       @CEP = ?, 
                                       @DistrictGuidId = ?,
                                       @ImportName = ?,
                                       @ImportID = ?"

query <- gsub("[[:space:]]+", " ", query)

con2 <- odbcConnect("database", uid="userid", pwd="password")

sqlExecute(con2, query, us11_12_00_school)

odbcClose(con2)

我得到R.这个错误

Error in sqlExecute(con2, query, us11_12_00_school) : 
  24000 0 [Microsoft][ODBC SQL Server Driver]Invalid cursor state
[RODBCext] Error: SQLExecute failed

如果我使用一个数据帧只有一行的量化代码工作。 还有其他人有这个问题吗? 有任何想法吗?

Answer 1:

好像你要使用仅第一列us11_12_00_school -你在函数的环通版与us11_12_00_school[i,] 。 在尽管矢量化版本,传递在整个数据帧!

我还没有测试出来,但我想通过为数据帧us11_12_00_school[1,]在向量化版本将得到预期的结果?



Answer 2:

我用下面的代码,并且似乎运作良好。 希望它可以帮助你。

require(RODBC)
require(RODBCext)

ExecuteQuery <- function(query, arguments){

  dbhandle <- odbcDriverConnect('driver={SQL Server Native Client 11.0};server=SereverName;database=DbName;trusted_connection=yes')
  if(missing(arguments))
    result <- sqlExecute(dbhandle, query = query, fetch = TRUE)  
  else
    result <- sqlExecute(dbhandle, query =query, data=arguments, TRUE)  
  close(dbhandle)
  return(result)
}

CallProcWithSomeParams <- function(param1, param2){

  ExecuteQuery('exec dbo.procName ?, ?', data.frame(param1, param2))
}


文章来源: Using R with RODBCext and RODBC to execute a SQL stored procedure