在 RTVS 中使用 R 执行 SQL 存储过程时出错

Error when Executing SQL Stored procedure with R In RTVS

我在 RTVS Visual Studio 2017 中使用 R 创建了一个存储过程,将其发布到我的数据库后,我在尝试执行它时遇到此错误:

Msg 39004, Level 16, State 20, Line 4
A 'R' script error occurred during execution of 'sp_execute_external_script' with HRESULT 0x80004004.

Msg 39019, Level 16, State 1, Line 4
An external script error occurred: Error in library(RODBC) : there is no package called 'RODBC' Calls: source -> withVisible -> eval -> eval -> library

Error in ScaleR. Check the output for more information. Error in eval(expr, envir, enclos) : Error in ScaleR. Check the output for more information. Calls: source -> withVisible -> eval -> eval -> .Call Execution halted

Msg 11536, Level 16, State 1, Procedure SqlSProc, Line 4 [Batch Start Line 2] > EXECUTE statement failed because its WITH RESULT SETS clause specified 1 result set(s), but the statement only sent 0 result set(s) at run time.

这是我的 SqlSProc.R 代码:

library(RODBC)
channel <- odbcDriverConnect(settings$dbConnection1)
InputDataSet <- sqlQuery(channel, iconv(paste(readLines('c:/users/abdal/source/repos/correlation/correlation/sqlsproc.query.sql', encoding = 'UTF-8', warn = FALSE), collapse = '\n'), from = 'UTF-8', to = 'ASCII', sub = ''))
odbcClose(channel)
InputDataSet$OtherLangDescription <- as.factor(InputDataSet$OtherLangDescription)
orderList <- unique(InputDataSet$OtherLangDescription)
ListId <- lapply(orderList, function(x) subset(InputDataSet, OtherLangDescription == x)$WHWorkOrderHeaderId)
Initial_Tab <- lapply(ListId, function(x) subset(InputDataSet, WHWorkOrderHeaderId %in% x)$OtherLangDescription)
Correlation_Tab <- mapply(function(Product, ID) table(Product) / length(ID),
                        Initial_Tab, ListId)
colnames(Correlation_Tab) <- orderList
cor_per <- round(Correlation_Tab * 100, 2)
OutputDataSet <- data.frame(row = rownames(cor_per)[row(cor_per)], col = colnames(cor_per)[col(cor_per)], corr = c(cor_per))
OutputDataSet <- InputDataSet

SQL 查询检索 R 存储过程的数据:

SELECT
    WHWorkOrderHeaderId, OtherLangDescription
FROM   
    Warehouse.WHWorkOrderDetails 
INNER JOIN 
    Warehouse.WHWorkOrderHeader AS WHH ON Warehouse.WHWorkOrderDetails.WHWorkOrderHeaderId = WHH.ID 
INNER JOIN 
    Warehouse.StockItems ON Warehouse.WHWorkOrderDetails.StockItemId = Warehouse.StockItems.Id 
ORDER BY  OtherLangDescription ASC

SQL 过程模板:

CREATE PROCEDURE [SqlSProc]
AS
BEGIN
EXEC sp_execute_external_script @language = N'R'
    , @script = N'_RCODE_'
    , @input_data_1 = N'_INPUT_QUERY_'
--- Edit this line to handle the output data frame.
   WITH RESULT SETS (([product_1] Nvarchar(MAX),[Product_2] Nvarchar(Max),[Correlation] INT));
END ; 

您的错误信息

Error in library(RODBC) : there is no package called 'RODBC'

指向一个丢失的包,在使用之前必须安装它:

install.packages("RODBC")
library(RODBC)
[Rest of your R-code]

以下错误很可能与丢失的包有关。预期有一个结果集,但 SP 没有返回结果...