I have a Question and Answer table in SQL Server 2008 R2.
Question:
q_id
question_text
Answer:
a_id
question_text
answer_text
This is obviously bad design. The question_text field is duplicated in the Question and Answer tables and there is no foreign key relationship between Answer and Question. I want to create this relation by finding the Question (the q_id) for each Answer that is already present in the Answer table. I would do this by matching the question_text value that is copied to the Answer table to the rows in the Question table.
This is what I’d like to do in pseudo code.
- create a nullable
q_idfield in theAnswertable (nullable because there is already data in theAnswertable) - select everything from the
Answertable. - for each row in the result
— select the corresponding question from theQuestiontable by comparing thequestion_textvalue.
— insert theq_idinto the nullableq_idcolumn in theAnswertable - change the
q_idcolumn in theAnswerto not nullable.
Could you help me achieve this in SQL Server 2008 R2? Thanks.
PS: All question_text values in the Question table are unique.
Try to:
Once done, add constraints on
NewAnswer, renameAnswerto something else andNewAnswertoAnswer.[edit: fix syntax, according to this link]