简体   繁体   中英

R function within SQL stored procedure issue

I'm attempting to set up a simple R function using SQL stored procedure but I can't get it to work without errors.

Here is my script

CREATE PROCEDURE sp_aggregate (@paramGroup nvarchar(40))
AS

EXECUTE sp_execute_external_script
@language =N'R',
@script=N'

library(dplyr)

data <- data.frame(x = c(1,2,3,4,5,6,7,8,9,10), Country = c("A", "A","A","A","A", 
"B", "B", "B", "B", "B"), Class = c("C", "C", "C", "C", "C", "D", "D", "D", "D", "D"))

agg_function <- function(df, column) {

    enq_column <- enquo(column)

    output <- df %>% group_by(!!enq_column) %>% summarize(total = sum(x))
    return(output)
 }  

 OutputDataSet <- as.data.frame(agg_function(df = data, column = paramgroup_var))

'
  , @input_data_1 = N''
 -- , @input_data_1_name = N'SQL_input' 
  , @output_data_1_name = N'OutputDataSet' 
  , @params = N'@paramgroup_var nvarchar(40)'
  , @paramgroup_var = @paramGroup;
GO

Execute sp_aggregate @paramGroup = Country

This is the error I'm running into:

Error in grouped_df_impl(data, unname(vars), drop) : 
Column `paramgroup_var` is unknown
Calls: source ... group_by.data.frame -> grouped_df -> grouped_df_impl

Error in execution.  Check the output for more information.
Error in eval(ei, envir) : 
Error in execution.  Check the output for more information.
Calls: runScriptFile -> source -> withVisible -> eval -> eval -> .Call
Execution halted

The error is from missing a ) at the end of the data.frame()

CREATE PROCEDURE sp_aggregate (@paramGroup nvarchar(40))
AS

EXECUTE sp_execute_external_script
@language =N'R',
@script=N'
library(dplyr)

data <- data.frame(x = c(1,2,3,4,5,6,7,8,9,10), 
                   Country = c("A", "A","A","A","A", "B", "B", "B", "B", "B"), 
                   Class = c("C", "C", "C", "C", "C", "D", "D", "D", "D", "D"))

agg_function <- function(df, column) {
  enq_column <- enquo(column)
  output <- df %>% group_by(!!enq_column) %>% summarize(total = sum(x))
  return(output)
}  

OutputDataSet <- as.data.frame(agg_function(df = data, column = paramgroup_var))

'
  , @input_data_1 = N''
 -- , @input_data_1_name = N'SQL_input' 
  , @output_data_1_name = N'OutputDataSet' 
  , @params = N'@paramgroup_var nvarchar(40)'
  , @paramgroup_var = @paramGroup;
GO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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