代码之家  ›  专栏  ›  技术社区  ›  wibeasley

使用odbc/DBI从R中的存储过程结果检索输出

  •  4
  • wibeasley  · 技术社区  · 8 年前

    我试图调用存储过程并检索输出。我正在使用调用SQL Server DBI -合规 odbc 包裹如何使用此软件包?以下代码返回受影响的行数。

    sql     <- "EXEC schema.prc_person @name_first='bob'"
    channel <- DBI::dbConnect(odbc::odbc(), dsn="db-remote")
    guy     <- DBI::dbExecute( channel, sql)
    DBI::dbDisconnect(channel); rm(channel)
    

    存储过程基本上是 SELECT 查询,但封装了一些计算,这就是为什么这不是一个直接的查询。

    SELECT value 
    FROM schema.tbl_person
    WHERE name_first=@name_first --plus some other stuff in the WHERE clause
    

    作为参考,这两条语句满足我的需要(使用 RODBC 和 RODBCext 包装)。也在 odbc 包裹,我试过了 dbCallProc() , dbSendQuery() 和 dbSendStatement() .

    channel <- RODBC::odbcConnect(dsn="db-remote")
    guy     <- RODBCext::sqlExecute(channel, "EXEC schema.tbl_person @name_first='bob'", fetch=T) # Notice the 'fetch' parameter
    RODBC::odbcClose(channel); rm(channel)
    
    channel <- RODBC::odbcConnect(dsn="db-remote")
    guy     <- RODBC::sqlQuery(channel, "EXEC schema.tbl_person @name_first='bob'")
    RODBC::odbcClose(channel); rm(channel)
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Scarabee    8 年前

    您可以使用 dbGetQuery :

    sql     <- "EXEC schema.prc_person @name_first='bob'"
    channel <- DBI::dbConnect(odbc::odbc(), dsn="db-remote")
    guy     <- DBI::dbGetQuery(channel, sql)
    DBI::dbDisconnect(channel); rm(channel)