2016-07-28 107 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; 

隨意讓我知道,如果這足以回答你的問題。如果需要,我可以提供更具體的幫助。

相關問題