0

i have following code, for this i have two tables, one table contain questions and another table contain answers. answers table something like following : (ans_question_1 to ans_question_95)

| answersId| ans_question_1| ans_question_2| student_id
|-----------|------------ |--------- |
| 1 | Male | 23 |11
| 2 | Female | 21 |12

Questions table (questions 1 to 95)

| question_id | Question| 
|----------- |-------- 
| 1 | Gender 
| 2 | Area code 

Want table something like this (need stored procedure with parameter student_id) i also need this table creation dynamically, because my number of questions change regularly.

| student_id | Gender | Area Code
|----------- |-------- -|--------
| 11 | Male | 23
| 12 | Female | 21
asked Apr 24, 2017 at 9:46

1 Answer 1

2

Using same stored procedure from previous answer, you can generate a new columns names, casting ans_question_xx with the name of each question.

create procedure getStudentAnswers(StudentId int)
begin
 set @cols := (select group_concat('ans_question_',
 cast(question_id as char(20)), 
 ' as ', 
 question separator ', ') 
 from questions); 
 set @sql = concat('select student_id, ', 
 @cols, 
 ' from answers
 where student_id = ', cast(StudentId as char(20)), 
 ' order by student_id;');
 PREPARE dynamic_statement FROM @sql;
 EXECUTE dynamic_statement;
 set @sql := null;
 set @cols := null;
 DEALLOCATE PREPARE dynamic_statement;
end \\
call getStudentAnswers(11);
call getStudentAnswers(12);
| student_id | Gender | Area_code | Another_question |
|------------|--------|-----------|------------------|
| 11 | Male | 23 | |
| student_id | Gender | Area_code | Another_question |
|------------|--------|-----------|------------------|
| 12 | Female | 21 | null |

Rextester here

answered Apr 24, 2017 at 9:47
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.