2016-07-28 66 views
-2

我如何插入到包含xml的TSQL文本字段。如何插入到MSSQL文本数据类型字段为xml

我可以在使用MSSQL作为后端的应用程序之一中创建自定义字段。当我创建这些自定义字段时,所有字段都会转到名为MIITEM的表中名为fldxml的单个字段。我想写插入和更新语句,但我不知道如何插入记录到fldxml场之间<field></field>

<field1></field1> is custFld1(Custom Field1) 
<field2></field2> is custFld2(Custom Field2) 
<field3></field3> is custFld3(Custom Field3) 
<field4></field4> is custFld4(Custom Field4) 

这里的数据看起来像在场上

<fields><field3>PFB652S6</field3><field1></field1><field2></field2><field4></field4></fields> 

enter image description here

这里是数据类型

enter image description here

+2

请勿使用文本数据类型。它已被弃用赞成varchar(max)超过十年。文本数据类型非常难以使用。对于手头的问题,我不明白你想要做什么,你发布的样本“xml”不是有效的xml。 –

回答

0

事实上,你不应该使用TEXT数据类型。为此,请使用XML代替。

无论数据类型如何,您都可以使用TSQL XML DML功能修改TSQL中的XML。这使得可以编写像INSERT,MODIFY,DELETE这样的DML语句来修改XML文档。

下面是一个例子证明这对您的文档:

-- First declare a variable of type XML 
DECLARE @fields xml; 

-- Here are the values we will be manipulating 
DECLARE @nodeToReplace VARCHAR(MAX),@newValue VARCHAR(MAX) 
SET @nodeToReplace = 'field3' 
SET @newValue = 'PFB652S6' 

-- Then fetch the value from the database. Insert the correct where clause 
SELECT @fields=CAST(fldxml AS XML) FROM MIITEM WHERE ..... 

-- Now @fieds will contain your XML 
SELECT @fields AS OldValue; 

-- When the value of the node is empty, you have to insert the text node as follows. 
SET @fields.modify(' 
    insert text {sql:variable("@newValue")} as last into (/fields/*[ local-name()=sql:variable("@nodeToReplace") ])[1] 
'); 
SELECT @fields AS NewInsertedValue; 

-- When the value is present already, a slightly different syntax must be used to update it 
SET @newValue = 'BLABLA' 
SET @fields.modify(' 
    replace value of (/fields/*[local-name()=sql:variable("@nodeToReplace")][1]/text())[1] 
    with  sql:variable("@newValue") 
'); 
SELECT @fields AS NewUpdatedValue; 

随意让我知道,如果这足以回答你的问题。如果需要,我可以提供更具体的帮助。

相关问题