2017-02-28 69 views
1

我有一個包含XML列的表,用於存儲文件詳細信息。現在我想根據值更新KB或MB中XML列的大小節點。將單元追加到SQL Server中的XML列值

樣本數據:

<FileInfo> 
    <Field Name="Filename">PV_1_PV_4126_C-482N-25457-005_V1.pdf</Field> 
    <Field Name="Created">02/21/2017</Field> 
    <Field Name="Modified">02/21/2017</Field> 
    <Field Name="Uploaded By">2120</Field> 
    <Field Name="Uploaded On">02/21/2017</Field> 
    <Field Name="Size">755</Field> 
</FileInfo> 

預期結果:

<FileInfo> 
    <Field Name="Filename">PV_1_PV_4126_C-482N-25457-005_V1.pdf</Field> 
    <Field Name="Created">02/21/2017</Field> 
    <Field Name="Modified">02/21/2017</Field> 
    <Field Name="Uploaded By">2120</Field> 
    <Field Name="Uploaded On">02/21/2017</Field> 
    <Field Name="Size">755 KB</Field> 
</FileInfo> 

樣本數據:

<FileInfo> 
    <Field Name="Filename">PV_1_PV_4126_C-482N-25457-005_V1.pdf</Field> 
    <Field Name="Created">02/21/2017</Field> 
    <Field Name="Modified">02/21/2017</Field> 
    <Field Name="Uploaded By">2120</Field> 
    <Field Name="Uploaded On">02/21/2017</Field> 
    <Field Name="Size">1024</Field> 
</FileInfo> 

預期結果:

<FileInfo> 
    <Field Name="Filename">PV_1_PV_4126_C-482N-25457-005_V1.pdf</Field> 
    <Field Name="Created">02/21/2017</Field> 
    <Field Name="Modified">02/21/2017</Field> 
    <Field Name="Uploaded By">2120</Field> 
    <Field Name="Uploaded On">02/21/2017</Field> 
    <Field Name="Size">1 MB</Field> 
</FileInfo> 

回答

2

您可以使用更新CTE

DECLARE @dummy TABLE(YourXMLColumn XML); 
INSERT INTO @dummy VALUES 
(
    N'<FileInfo> 
     <!--More fields--> 
     <Field Name="Size">755</Field> 
    </FileInfo> ' 
) 
,(
    N'<FileInfo> 
     <!--More fields--> 
     <Field Name="Size">1024</Field> 
    </FileInfo> ' 
); 

WITH ReplaceValue AS 
(
    SELECT YourXMLColumn 
      ,ca2.newSize 
    FROM @dummy AS d 
    CROSS APPLY(SELECT d.YourXMLColumn.value(N'(/FileInfo/Field[@Name="Size"]/text())[1]',N'int')) AS ca1(size) 
    CROSS APPLY(SELECT CASE WHEN ca1.size % 1024=0 
          THEN CAST(ca1.size/1024 AS VARCHAR(10)) + ' MB' 
          ELSE CAST(ca1.size AS VARCHAR(10)) + ' KB' END) AS ca2(newSize) 
) 
UPDATE ReplaceValue SET YourXMLColumn.modify(N'replace value of (/FileInfo/Field[@Name="Size"]/text())[1] with sql:column("newSize")'); 

SELECT * FROM @dummy; 

首先,我讀了「大小」字段的值。如果它可以被1024分隔,它將被寫爲「MB」,否則該值保持爲「KB」。

最終的UPDATE將更新CTE,但這實際上會影響表列。 SELECT顯示修改後的表格數據。