0

I am very much new to Amazon redshift. I am trying to create the UDF function to create column aggregation by adding multiple columns, here is what I am tried

CREATE OR REPLACE FUNCTION pp_calc(identifier varchar(100),table_name varchar(100))
RETURNS float 
stable 
as $$

BEGIN

IF identifier ='OC' THEN
  EXECUTE 'SELECT identifier'||_1 + || 'identifier' ||_2 || 'FROM ' || table_name /* I want to return this addition result */
ELSE 
  'SELECT identifier'||_1 + || 'identifier' ||_2 || 'FROM ' || table_name
END IF;

END;

$$ LANGUAGE sql;

Errors I am getting near return statement. I am sure there is something wrong with syntax. I want to pass the indentifer as parameter based on parameter I want to add columns.

2
  • 1
    I don't know about Redshift, but in Postgres you can only use dynamic sql in PL/pgSQL, not in language sql functions Commented Jan 13, 2021 at 14:14
  • Yes I tried that as well, I am getting error [Amazon](500310) Invalid operation: language plpgsql not supported for CREATE FUNCTION; Commented Jan 13, 2021 at 14:20

1 Answer 1

1

You need to use a stored procedure to perform dynamic SQL. See "Overview of Stored Procedures in Amazon Redshift"

CREATE PROCEDURE pp_calc(identifier varchar(100),table_name varchar(100))
RETURNS float  
AS $$
BEGIN
IF identifier ='OC' THEN
  EXECUTE 'SELECT '||identifier||'_1 + '||identifier||'_2 FROM '||table_name ;
/* I want to return this addition result */
ELSE
  EXECUTE 'SELECT '||identifier||'_1 + '||identifier||'_2 FROM '||table_name ;
END IF;
END;
$$ LANGUAGE plpgsql;

See also this previous answer: Redshift: Executing a dynamic query from a string

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.