sqlstored-procedureshanastring-agg

SAP HANA SQL store STRING_AGG to variable in procedure


I have a procedure where I need to get the fields of a column (in SAP HANA database). I need to assign the output of STRING_AGG function to a variable

CREATE procedure TAB_COMP (IN T1 VARCHAR(30), IN T2 VARCHAR(30))
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER

AS
BEGIN

DECLARE TAB1 TABLE (COLUMN_NAME VARCHAR(500));
DECLARE TAB2 TABLE (COLUMN_NAME VARCHAR(500));

DECLARE COLS1 VARCHAR(500);
DECLARE COLS2 VARCHAR(500);

TAB1 = SELECT COLUMN_NAME FROM TABLE_COLUMNS WHERE TABLE_NAME= :T1 ORDER BY POSITION;
TAB2 = SELECT COLUMN_NAME FROM TABLE_COLUMNS WHERE TABLE_NAME= :T2 ORDER BY POSITION;
 
COLS1 := SELECT STRING_AGG(COLUMN_NAME,',') FROM :TAB1;

END

I'm getting an error with the COLS1 := SELECT STRING_AGG(COLUMN_NAME,',') FROM :TAB1; line. Can you figure out why its happening?


Solution

  • To assign a single value (scalar) result from a query to a variable, use the SELECT INTO command.

    SELECT 
          STRING_AGG(COLUMN_NAME,',') INTO COLS1
    FROM :TAB1;