Hey there. Me again with another issue that I'm probably just over-thinking:I need to create a table of users and their answers to a questionnaire. I need the output to look like this:userID | userNAME | 1 | 2 | 3 | 4 ------------------------------------------- 1 | John | Yes | NULL | Yes | No 2 | Mike | Yes | No | Yes | Yes
Questions that are not answered are not in the database and should return a NULL (As shown above). and questions can be added at any time. The output should have a column for each of the questions (so in the example there's 4 questions. If a fifth question is added then there needs to be a fifth column.) The question columns can be either the questionID or the questionTEXT, that does not matter. The data is stored in 3 tables. a User table, a question table and an answers table.CREATE TABLE #users ( userID INT, userNAME VARCHAR(15))CREATE TABLE #questions ( questionID INT, questionTEXT varchar(255)) CREATE TABLE #answers ( answerID INT, userID INT, questionID INT, answerTEXT VARCHAR(255))
Sample data is as follows:INSERT INTO #users (userID, userNAME) VALUES (1,'John')INSERT INTO #users (userID, userNAME) VALUES (2,'Mike')INSERT INTO #questions (questionID, questionTEXT) VALUES (1,'Do you...')INSERT INTO #questions (questionID, questionTEXT) VALUES (2,'Can you...')INSERT INTO #questions (questionID, questionTEXT) VALUES (3,'Will you...')INSERT INTO #questions (questionID, questionTEXT) VALUES (4,'Did you...')INSERT INTO #answers (answerID, userID, questionID, answerTEXT) VALUES (1,1,1,'Yes')INSERT INTO #answers (answerID, userID, questionID, answerTEXT) VALUES (2,1,3,'Yes')INSERT INTO #answers (answerID, userID, questionID, answerTEXT) VALUES (3,1,4,'No')INSERT INTO #answers (answerID, userID, questionID, answerTEXT) VALUES (4,2,1,'Yes')INSERT INTO #answers (answerID, userID, questionID, answerTEXT) VALUES (5,2,2,'No')INSERT INTO #answers (answerID, userID, questionID, answerTEXT) VALUES (6,2,3,'Yes')INSERT INTO #answers (answerID, userID, questionID, answerTEXT) VALUES (7,2,4,'Yes')
What's the best way to accomplish this in MS SQL 2000? I have tried using multiple cursors (One to build a temp table with dynamic column names and another to build and execute INSERT statements, but it isn't looping through all the rows. I'm curious if there's an easier way to do this.Thanks in advance!