简体   繁体   English

R,使用RJDBC调用SQL Server存储过程

[英]R, Call a SQL Server stored procedure with RJDBC

I would like to call a stored procedure from a function in R. See my code below. 我想从R中的函数调用存储过程。请参见下面的代码。 unfortunately this code only generates a dataframe without values in it. 不幸的是,这段代码只生成一个没有值的数据框。 I would like to fix this with RJDBC & DBI , since there seems to be a problem with RODBC . 我想与解决这个RJDBCDBI ,因为似乎有一个问题RODBC

 RPT_09_Hourly_Connected_v3<- function(Year, Month="NULL",State = "NULL",Region="NULL", City="NULL", District="NULL", Subdistrict="NULL" ,Address='NULL'){
  drv <- JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver", "/opt/sqljdbc_3.0/sqljdbc4.jar") 
  conn <- DBI::dbConnect(drv, "jdbc:sqlserver://***;databaseName=***;user=***;password=***")
  sqlText <- paste("exec [dbo].[RPT_09_Hourly_Connected_v3]@Year=",Year, 
                                                   ",@Month=",Month,
                                                   ",@State=",State,"",
                                                   ",@Region=",Region,"",
                                                   ",@City=N'",City,"'",
                                                   ",@District=",District,"",
                                                   ",@Subdistrict=",Subdistrict,"",
                                                   ",@Address=N'",Address,"'",
                                                   sep="")
  data <- RJDBC::dbGetQuery(conn,sqlText)
}
a<- RPT_09_Hourly_Connected_v3(Year = 2016)

> str(a)
'data.frame':   0 obs. of  9 variables:
 $ Regio          : chr 
 $ Stad           : chr 
 $ Stadsdeel      : chr 
 $ Buurtcombinatie: chr 
 $ Adres          : chr 
 $ Jaar           : num 
 $ Maand          : num 
 $ hourNR         : num 
 $ HoursConnected : num

This worked for me before RODBC crashed. RODBC崩溃之前,这对我RODBC Is there any difference between RODBC and RJDBC ? RODBCRJDBC之间有什么区别吗?

RPT_09_Hourly_Connected_v3<- function(Year, Month="NULL",State = "NULL",Region="NULL", City="NULL", District="NULL", Subdistrict="NULL" ,Address='NULL'){
  dbhandle <- odbcConnect("***;DATABASE=***;UID=***;PWD=***")
  data <- sqlQuery(dbhandle,paste("exec [ dbo].[RPT_09_Hourly_Connected_v3]@Year=",Year,
                                  ",@Month=",Month,
                                  ",@State=",State,"",
                                  ",@Region=",Region,"",
                                  ",@City=N'",City,"'",
                                  ",@District=",District,"",
                                  ",@Subdistrict=",Subdistrict,"",
                                  ",@Address=N'",Address,"'",
                                  sep=""))
  odbcCloseAll()
  data
}

If I execute the stored procedure in SQL Server by hand it will look like this: 如果我手动执行SQL Server中的存储过程,它将如下所示:

EXEC    @return_value = [dbo].[RPT_09_Hourly_Connected_v3]
        @Year = 2016,
        @Month = NULL,
        @State = NULL,
        @Region = NULL,
        @City = N'Amsterdam',
        @District = NULL,
        @Subdistrict = NULL,
        @Address = NULL

Can you explain what's wrong and how to fix it? 您能否解释出什么问题以及如何解决?

I find the RODBCext a lot easier to use since it uses parameter binding. 我发现RODBCext易于使用,因为它使用了参数绑定。 It also makes it easier to use NA in place of "NULL" and eliminates the concern about matching up the quote characters correctly. 它还使使用NA代替"NULL"变得更容易,并且消除了正确匹配引号字符的麻烦。

library(RODBCext)
RPT_09_Hourly_Connected_v3<- function(Year, Month=NA, State = NA, Region=NA, City=NA, District=NA, Subdistrict=NA ,Address=NA){
  ch <- odbcDriverConnect([connection_string])

  sqlText <- paste("exec [dbo].[RPT_09_Hourly_Connected_v3]@Year=? ", 
                                                   ",@Month=? ",
                                                   ",@State=? ",
                                                   ",@Region=? ",
                                                   ",@City=? ",
                                                   ",@District=? ",
                                                   ",@Subdistrict=? ",
                                                   ",@Address=? ",
                                                   sep="")
  sqlExecute(channel = ch,
    query = sqlText,
    data = list(Year, Month, State, Region, City, District, Subdistrict, Address),
    fetch = TRUE,
    stringAsFactors = FALSE)
}

I found a very easy solution, and I wish I knew this before! 我找到了一个非常简单的解决方案,但愿我以前知道这一点! Maybe I can help someone else with my answer. 也许我可以帮助别人解决我的问题。

FACT_CHARGESESSION<- function (username, password, country = "NULL",state = "NULL", region = "NULL",city = "NULL",
                           district  = "NULL",subdistrict = "NULL", provider= "NULL",startDateView = "NULL",endDateView = "NULL") {



InstallCandidates <-c("DBI","rJava","RJDBC","dplyr")
  toInstall<-InstallCandidates[!InstallCandidates %in% library()$results[,1]]
  if(length(toInstall) !=0){install.packages(toInstall,repos="http://cran.r-project.org")}
  lapply(InstallCandidates,library,character.only=TRUE)
  rm("InstallCandidates","toInstall")

  NAME <- "dbo.R_00_ValidTransactions_ID_PW_v4"
  options(java.parameters = "- Xmx1024m")
  drv <- JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver", "/opt/sqljdbc_3.0/sqljdbc4.jar")
  conn <- dbConnect(drv, "jdbc:sqlserver://***.**.***.***;databaseName=****;user=***;password=***")
  # Make a SQL text 
  sqlText <- paste(NAME, paste(username,password, country,state,region,city,district,subdistrict,provider,startDateView,endDateView,sep=",")) 
  data <- dbGetQuery(conn,sqlText)

  return(data)
}

output of sqlText: sqlText的输出:

"dbo.R_00_ValidTransactions_ID_PW_v4 M.Kooi , Stackoverflow , NULL , NULL , Amsterdam , NULL , NULL , NULL , NULL , NULL , NULL "

Instead of using the SP execute window you just execute now the SP with the paremters in a new query window. 现在不用执行SP执行窗口,而只需在新的查询窗口中执行带有参数的SP。

I've used this in the past successfully with RJDBC : 我过去在RJDBC成功使用了RJDBC

d <- dbGetQuery(conn, paste0("exec my_STOREDPROC @Field1= '",Field1,"';"))

It might be simply a matter of syntax. 这可能只是语法问题。 Hard to tell w/oa reproducible example. 很难说出可重复的例子。 Note the extra set of quotes . 注意额外的引号集

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM