如何批量更新SQL Server数据库中的列?
情况如下:我有一个被定义为nvarchar(max)
的列Config
,但它包含格式化的XML.
下面是一个例子:
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfLearningPathItem xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<LearningPathItem xsi:type="type">
<Id>id</Id>
<Title>title</Title>
<Content><iframe allowfullscreen src="https://site.sharepoint.com/sites/site/SitePages/page.aspx" width="100%" height="100%" data-embedSize="3"></iframe></Content>
<EmbedType>typeType</EmbedType>
</LearningPathItem>
</ArrayOfLearningPathItem>
我需要批量更新内容元素,这样代码将被删除,只有URL应该留下来.
所以从这个例子中,结果应该是
<Content>https://site.sharepoint.com/sites/site/SitePages/page.aspx</Content>
我try 将列转换为XML,将其放到临时表中,搜索具有SharePoint链接的所有元素并使用新内容更新它们,然后将临时表与旧表连接起来.
然而,我仍然找不到从代码中删除URL的方法.对于其他元素来说,这更容易,如果我只更改EmbedType参数,它就可以很好地工作:
UPDATE @TempTable
SET ConfigXML.modify('
replace value of (/ArrayOfLearningPathItem/LearningPathItem[EmbedType="type1" and Content[contains(text()[1], "sharepoint.com")]]/EmbedType/text())[1]
with
"type2"
');
对于URL,我猜应该是这样的,如果在XML Modify方法中可以使用子字符串-BEFORE和SUBSTRING-AFTER,但只能使用子字符串
UPDATE @TempTable
SET ConfigXML.modify('
replace value of (/ArrayOfLearningPathItem/LearningPathItem[EmbedType="type1" and Content[contains(text()[1], "sharepoint.com")]]/Content/text())[1]
with
substring-before(substring-after(/ArrayOfLearningPathItem/LearningPathItem[EmbedType="type1" and Content[contains(text()[1], "sharepoint.com")]]/Content/text(), "src=""), """)
');