Troubleshooting on Dynamic SQL in MySQL

pratikrrana
edited January 2023 in Magic ETL

Hello,

I am working on to create dynamic sql in MySQL. Bottom line for my query is, I would like to create column for each question and display answer associated with it in row for each application.

This query is keep giving me an error. Can someone look into this and make some suggestion?

Also, is there a way where we can PRINT this dynamic query before execution?

SET @sql = NULL;

SELECT

 GROUP_CONCAT(DISTINCT

  CONCAT(

   'sum(case when x.question_text = ''',

   question_text,

   ''' then x.answer_text end) AS ',

   question_text, '`'

  )

 ) INTO @sql

from

(SELECT DISTINCT aa.application_id,aq.question_text,aa.answer_text

from table_a aq

inner join table_b aa on aa.application_question_id = aq.id 

where aq.program_id = 136)x;


SET @sql 

 = CONCAT('SELECT aa.application_id, ', @sql, ' 

from table_a aq

inner join table_b aa on aa.application_question_id = aq.id 

      group by aa.application_id;');

      

PREPARE stmt FROM @sql;


EXECUTE stmt;


DEALLOCATE PREPARE stmt;