2017-03-08 70 views
0

我試圖通過存儲過程從SQL Server運行基本R腳本。我正在返回一個數據集,也想返回/輸出一個變量,但我無法做到這一點。如何從SQL Server運行R時返回變量

下面是存儲過程我有

DROP PROC IF EXISTS get_iris_dataset; 
go 
CREATE PROC get_iris_dataset 
AS 
BEGIN 
declare @OutName float 
EXEC sp_execute_external_script 
    @language = N'R' 
, @script = N' 
    iris_data <- iris 
    out = 5.1;' 
, @input_data_1 = N'' 
, @output_data_1_name = N'iris_data' 
,@params= N'@out float OUTPUT' 
,@out = @OutName OUTPUT 

WITH RESULT SETS (("Sepal.Length" float not null, 
     "Sepal.Width" float not null, 
    "Petal.Length" float not null, 
    "Petal.Width" float not null, "Species" varchar(100))); 
END; 
return 0 
go 

我打電話如下步驟:

declare @OutputVar float 
exec @OutputVar = get_iris_dataset 
print @OutputVar 

它確實輸出的數據集,但我不能夠存儲的值OutputVar中。

即使不輸出數據集,我也不能返回OutputVar的值,只嘗試捕獲OutputVar的值。 任何幫助表示讚賞。

在此先感謝!

+0

我這裏看不到任何R代碼裏面。 –

+0

R代碼只有2行。 iris_data < - iris, out = 5.1; –

回答

1

我要做的就是使用StoredProcedure函數(sqlrutils包的一部分,它是MS R Server 9.0.1的一部分)將R代碼包裝到存儲過程中。這與您的原始代碼略有不同,因爲返回值被封裝在一個列表中。但這個想法仍然是一樣的。

library(sqlrutils) 

testfunc <- function() 
{ 
    iris_dataset <- iris 
    out <- 5.1 
    list(iris_dataset=iris_dataset, out=out) 
} 

sp <- StoredProcedure(testfunc, "spTestFunc", 
    OutputData("iris_dataset"), 
    OutputParameter("out", "numeric"), 
    connectionString="<your_connection_string>") 

registerStoredProcedure(sp) 

已經這樣做了,在SSMS的PROC你可以單擊鼠標右鍵,選擇「執行存儲過程」,並SSMS會產生一些代碼給你。該代碼將是這樣的:

USE [databasename] 
GO 

DECLARE @return_value int, 
     @out_outer float 

EXEC @return_value = [dbo].[spTestFunc] 
     @out_outer = @out_outer OUTPUT 

SELECT @out_outer as N'@out_outer' 

SELECT 'Return Value' = @return_value 

GO 

如果你只想打印編號,就可以到這個簡化代碼:

DECLARE @out_outer float 

EXEC [dbo].[spTestFunc] 
     @out_outer = @out_outer OUTPUT 

SELECT 'Return Value' = @out_outer 
GO 
+0

感謝您的幫助,但由於我是在SQL Server中使用R的新手,我有點困惑。我不確定如何運行代碼的第一部分(即以library(sqlrutils)開始並以registerStoredProcedure(sp)結尾)。 我是否在SSMS中運行這段代碼,而沒有將它包裹在任何東西中?請幫忙。 –

+0

該代碼是R代碼。你在R會話中運行它。 –

+0

我是否創建任何連接字符串,以便R知道寫入/保存此存儲的Proc的位置? –