SQL存储过程中调用R函数执行报错,寻求解决方案
paramgroup_var is unknown" Error in SQL Stored Procedure Calling R Function Let's break down why you're hitting this error and how to fix it quickly:
Why the Error Happens
Your R function uses enquo(column) which expects a bare symbol (like a raw column name, e.g., Country), but you're passing a string value ("Country") via the SQL parameter @paramgroup_var. When enquo processes paramgroup_var, it looks for a column literally named paramgroup_var in your data frame—which doesn't exist, hence the error.
Solution 1: Convert String to Symbol with sym()
Modify your R function to convert the input string to a symbol before using it in group_by:
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) { # Convert string input to a valid column symbol column_sym <- sym(column) output <- df %>% group_by(!!column_sym) %>% summarize(total = sum(x)) return(output) } OutputDataSet <- as.data.frame(agg_function(df = data, column = paramgroup_var)) ' , @input_data_1 = N'' , @output_data_1_name = N'OutputDataSet' , @params = N'@paramgroup_var nvarchar(40)' , @paramgroup_var = @paramGroup; GO -- Important: Pass the column name as a string (wrap in single quotes) Execute sp_aggregate @paramGroup = 'Country'
Solution 2: Use across() with all_of() (Modern dplyr Approach)
If you're using dplyr 1.0.0 or newer, you can skip symbol conversion entirely by using across() and all_of() to handle string column names directly—this is cleaner and more intuitive:
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) { # Use across() to directly handle string column names output <- df %>% group_by(across(all_of(column))) %>% summarize(total = sum(x)) return(output) } OutputDataSet <- as.data.frame(agg_function(df = data, column = paramgroup_var)) ' , @input_data_1 = N'' , @output_data_1_name = N'OutputDataSet' , @params = N'@paramgroup_var nvarchar(40)' , @paramgroup_var = @paramGroup; GO Execute sp_aggregate @paramGroup = 'Country'
Key Reminder
Don't forget to wrap your column name in single quotes when executing the stored procedure (@paramGroup = 'Country' instead of @paramGroup = Country). Without quotes, SQL will treat Country as an undefined variable rather than the string value your R function needs.
内容的提问来源于stack exchange,提问作者ari8888

