-1
我想創建一個具有varchar(max)
參數的存儲過程,該參數充當我在我的應用程序中構建的XML字符串的容器。我設法想出這將作爲varchar(max)
參數的存儲過程通過,將轉換爲XML的XML字符串:如何循環XML類型並在SQL Server中每次迭代插入記錄?
<SurveyQuestion>
<Name>What is your pets name?</Name>
<Type>1</Type>
<IsRequired>True</IsRequired>
<Answer></Answer>
</SurveyQuestion>
<SurveyQuestion>
<Name>What is your gender?</Name>
<Type>3</Type>
<IsRequired>True</IsRequired>
<Answer>Male</Answer>
<Answer>Female</Answer>
<Answer>Trans</Answer>
</SurveyQuestion>
<SurveyQuestion>
<Name>Which colors do you like?</Name>
<Type>4</Type>
<IsRequired>False</IsRequired>
<Answer>Yellow</Answer>
<Answer>Green</Answer>
<Answer>Red</Answer>
<Answer>Blue</Answer>
<Answer>Orange</Answer>
</SurveyQuestion>
<SurveyQuestion>
<Name>Rate the service that you have receive from 1 to 5. I being the lowest and 5 being the highest</Name>
<Type>2</Type>
<IsRequired>True</IsRequired>
<Answer>1</Answer>
<Answer>2</Answer>
<Answer>3</Answer>
<Answer>4</Answer>
<Answer>5</Answer>
</SurveyQuestion>
我有Questions
和Answers
表:
CREATE TABLE [dbo].[Questions]
(
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Question] [varchar](max) NULL, --Name
[IsRequired] bit NULL,
[SurveyFieldObjectId] [bigint] NULL --Type
)
CREATE TABLE [dbo].[Answers]
(
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[QuestionId] [bigint] NULL, --Foreign key Questions
[Options] [varchar](50) NULL, --Answer
[SurveyFieldObjectId] [bigint] NULL
)
這是我的存儲過程:
CREATE PROCEDURE
@otherIrrelevantProperty nvarchar(120),
@varcharXML varchar(max)
AS
BEGIN
BEGIN TRY
DECLARE @questionsXML = CAST(@varcharXML AS XML)
BEGIN TRANSACTION INSERTSURVEY
LOOP(@questionsXML.question)
BEGIN
INSERT INTO Questions VALUES (..)
LOOP(@questionsXML.answers)
BEGIN
INSERT INTO Answers VALUES (..)
END
END
COMMIT TRANSACTION INSERTSURVEY
SELECT 1
END TRY
BEGIN CATCH
IF (@@TRANCOUNT > 0)
BEGIN
ROLLBACK TRANSACTION INSERTSURVEY
END
SELECT -1
END CATCH
END
循環和遊標 - 甚至不是一次。 [查詢那些東西](https://docs.microsoft.com/sql/t-sql/xml/nodes-method-xml-data-type)。 –
'Name'是否是唯一的? –