本文介绍了SQL:递归更新表中的XML列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在SQL Server 2012中有一个表
使用以下列定义
CREATE TABLE [dbo].[tblStepList](
[ToDoId] [int] IDENTITY(1,1) NOT NULL,
[Data] [xml] NOT NULL
}
并且数据列是带有
的XML<Steplist>
<Step>
<StepId>e36a3450-1c8f-44da-b4d0-58e5bfe2a987</StepId>
<Rank>1</Rank>
<IsComplete>false</IsComplete>
<TextReadingName>bug-8588_Updated3</TextReadingName>
</Step>
<Step>
<StepId>4078c1b1-71ea-4578-ba61-d2f6a5126ba1</StepId>
<Rank>2</Rank>
<TextReadingName>reading1</TextReadingName>
</Step>
</Steplist>'
我想用新的XML更新表的每一行,以便在TextReadingID之后查找名为TextReadingID的新节点
我想插入一个名为TextReadingId值的新节点,我希望我的TextReadingId值是如下所示的数字
<Steplist>
<Step>
<StepId>e36a3450-1c8f-44da-b4d0-58e5bfe2a987</StepId>
<Rank>1</Rank>
<IsComplete>false</IsComplete>
<TextReadingName>bug-8588_Updated3</TextReadingName>
<TextReadingId>1</TextReadingId>
</Step>
<Step>
<StepId>4078c1b1-71ea-4578-ba61-d2f6a5126ba1</StepId>
<Rank>2</Rank>
<TextReadingName>reading1</TextReadingName>
<TextReadingId>1</TextReadingId>
</Step>
</Steplist>';
这就是我尝试的,但它没有按预期工作
DECLARE @i int;
SELECT
@i = s.data.value('count(/Steplist/Step)', 'nvarchar(max)')
FROM tblStepList s
SET data.modify('insert <TextReadingId>{sql:variable("@i")}</TextReadingId> as last into (/Steplist/Step[sql:variable("@i")])[1]')
print @i
End
推荐答案
请尝试以下解决方案。
它正在使用XQuery及其FLWOR表达式。
SQL
USE tempdb;
GO
DROP TABLE IF EXISTS [dbo].[tblStepList];
CREATE TABLE [dbo].[tblStepList](
[ToDoId] [int] IDENTITY(1,1) NOT NULL,
[Data] [xml] NOT NULL
);
INSERT INTO dbo.tblStepList ([Data]) VALUES
(N'<Steplist>
<Step>
<StepId>e36a3450-1c8f-44da-b4d0-58e5bfe2a987</StepId>
<Rank>1</Rank>
<IsComplete>false</IsComplete>
<TextReadingName>bug-8588_Updated3</TextReadingName>
</Step>
<Step>
<StepId>4078c1b1-71ea-4578-ba61-d2f6a5126ba1</StepId>
<Rank>2</Rank>
<TextReadingName>reading1</TextReadingName>
</Step>
</Steplist>');
-- before
SELECT * FROM dbo.tblStepList;
UPDATE dbo.tblStepList
SET [Data] = [Data].query('<Steplist>
{
for $x in /Steplist/Step
let $pos := count(Steplist/*[. << $x]) + 1
return <Step>{$x/*,
if (not($x/TextReadingId)) then <TextReadingId>{$pos}</TextReadingId>
else ()}
</Step>
}
</Steplist>');
-- after
SELECT * FROM dbo.tblStepList;
这篇关于SQL:递归更新表中的XML列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!