我正在读取存储过程中的xml文件,以将数据插入到现有表中。我已经在一个小测试中阅读了xml,看看我是否可以像我认为应该能够阅读它一样。我现在想要创建一个存储过程,在“问题”表和“答案”表中插入来自xml的数据。问题是我需要从问题表中创建的主键,以插入到答案表中,否则由于FK而导致问题。
我有这个:
insert into Questions(Question_Text, Questionaire_ID, QuestionType, Filter)
select
X.xmlData.query('Question').value('.', 'varchar(100)') Question_Text,--Question Text
X.xmlData.query('QuestionaireID').value('.', 'varchar(100)') Questionaire_ID,-- Questionaire ID
X.xmlData.query('Type').value('.', 'varchar(100)') WuestioneType,--Question TYPE
X.xmlData.query('Filter').value('.', 'varchar(100)') Filter--Filter
from
(select
cast(x as XML)
from openrowset(bulk 'C:\sqlXML.xml', single_blob) as T(x)
) as T(x)
cross apply
x.nodes('data/New') as X(xmlData);
select @newQuestionId = SCOPE_IDENTITY() <--I need this to know the current
questionID that relate to the following possible answers
insert into Possible_Answers(Question_ID, Possible_Answer_Text,
Explanation_Required, Review_Required, Question_Type)
select @newQuestionId ,
X.xmlData.query('AnswerChoice[1]').value('.', 'varchar(100)') Possible_Answer_Text,
X.xmlData.query('AnswerChoice[2]').value('.', 'varchar(100)') Possible_Answer_Text,
X.xmlData.query('AnswerChoice[3]').value('.', 'varchar(100)') Possible_Answer_Text,
X.xmlData.query('AnswerChoice[4]').value('.', 'varchar(100)') Possible_Answer_Text,
X.xmlData.query('ExplanationRequired').value('.', 'varchar(100)') Explanation_Required,
X.xmlData.query('ReviewRequired').value('.', 'varchar(100)') Review_Rewuired
from (
select cast(x as XML)
from openrowset(
bulk 'C:\sqlXML.xml',
single_blob) as T(x)
)
as T(x)
cross apply x.nodes('data/New') as X(xmlData);
现在这可能都是错的,因为在我的测试中我只是读取数据而没有将其插入表中。
这是我的XML:
<?xml version="1.0" encoding="UTF-8" ?>
<data>
<New>
<QuestionaireID>2</QuestionaireID>
<Type>1</Type>
<Question>Does this test work?</Question>
<Filter>31</Filter>
<AnswerChoice>true</AnswerChoice>
<AnswerChoice>false</AnswerChoice>
<ExplanationRequired></ExplanationRequired>
<ReviewRequired></ReviewRequired>
</New>
<New>
<QuestionaireID>3</QuestionaireID>
<Type>2</Type>
<Question>Does this test work really?</Question>
<Filter>127</Filter>
<AnswerChoice>answer A</AnswerChoice>
<AnswerChoice>Answer B</AnswerChoice>
<AnswerChoice>Answer C</AnswerChoice>
<AnswerChoice>Answer D</AnswerChoice>
<ExplanationRequired></ExplanationRequired>
<ReviewRequired></ReviewRequired>
</New>
</data>
正如您所看到的,对于2个可能的答案或4个可能的答案可能存在疑问......
我收到了错误:
INSERT语句不能包含为变量赋值的SELECT语句。
为变量赋值的SELECT语句不能与数据检索操作结合使用。
我知道错误的来源,但我想知道是否有办法做到这一点?