| Author |
Topic |
|
trabart
Starting Member
1 Post |
Posted - 2009-04-22 : 05:52:38
|
| We have a database where we store the multiple choice answers of students of the exams they have taken. Each exam can have 1 to n questions.We now have a query that creates the following output when we want to see the results of a certain Exam (ExamId =1):StudentId,ExamId,NumberOfQuestions,QuestionId,GivenAnswer1,1,3,1,A1,1,3,2,B1,1,3,3,C2,1,3,1,A2,1,3,2,A2,1,3,3,AI would now like to have a query that produces the following output for this particular exam:StudentId,ExamId,Answer1,Answer2,Answer31,1,A,B,C2,1,A,A,ASo basically what I'm trying to achieve is that the 'NumberOfQuestions' column in my first query will be used to generate the right number of Answer-columns in my 2nd query and that each student will then get his or her 'own' record. Is this at all possible without using dynamic sql? And if not: how can we build a stored procedure that limits the chance of sql injection? |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2009-04-22 : 06:38:30
|
| [code]DECLARE @T TABLE(StudentId INT,ExamId INT,NumberOfQuestions INT,QuestionId INT,GivenAnswer CHAR(2))INSERT INTO @t SELECT 1,1,3,1,'A'INSERT INTO @t SELECT 1,1,3,2,'B'INSERT INTO @t SELECT 1,1,3,3,'C'INSERT INTO @t SELECT 2,1,3,1,'A'INSERT INTO @t SELECT 2,1,3,2,'A'INSERT INTO @t SELECT 2,1,3,3,'A'SELECT studentid, examid , [1]AS 'Answer1',[2] AS 'Answer2',[3] AS 'Answer3'FROM @tPIVOT(MAX(givenanswer) FOR questionid IN ([1],[2],[3]))pSELECT studentid,examid, MAX(CASE WHEN questionid = 1 THEN givenanswer END) AS 'Answer1',MAX(CASE WHEN questionid = 2 THEN givenanswer END) AS 'Answer2',MAX(CASE WHEN questionid = 3 THEN givenanswer END) AS 'Answer3'FROM @tGROUP BY studentid,examid[/code] |
 |
|
|
|
|
|