在SQL Server中更新XML节点

时间:2015-11-09 19:22:27

标签: sql-server xml

我经历了与此主题相关的所有问题,我似乎无法在已经提供的内容中找到答案。

我要做的是在xml结构中插入一个新节点。当我运行下面的代码时,它不会发生错误,但XML不包含新插入的“材料”子部分。

你们中间有人会介意我在这里搞砸了吗?

 DECLARE @t TABLE (rowID int IDENTITY PRIMARY KEY, XmlData XML)

 INSERT INTO @t (XmlData)
VALUES ('
<Root>
<ProductDescription ProductID="01" ProductName="Widget">
    <Features>
        <Warranty>1 year</Warranty>
        <Maintenance>Monthly</Maintenance>
    </Features>
</ProductDescription>
</Root>
')

UPDATE @t
SET XmlData.modify('insert <Material /> as first into (/Features)[1]')

SELECT 'before' s, DATALENGTH(XmlData) dl, XmlData
FROM @t
WHERE rowId = 1

1 个答案:

答案 0 :(得分:2)

您需要将完整 XPath指定到要插入新XML片段的位置:

2003 1 1 18 0 -1 36 50 46
2003 1 2 16 3 -1 43 56 52
2003 1 3 19 7 -1 42 56 49
2003 1 4 14 3 -1 42 58 50

您需要使用

#include "library.h"
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

ifstream in;
int yr[364], mo[364], day[364], windSpeed[364], precip[364], snowDepth[364], minTemp[364], maxTemp[364], avgTemp[364];
int x_pos;
int y_pos;

int daySinceJan(int month, int dayOfMonth, int year) {
    int offset;

    if (month == 1 || month == 4 || month == 5) {
        offset = 0;
    }
    if (month == 2 || month == 6 || month == 7) {
        offset = 1;
    }
    if (month == 3) {
        offset = -1;
    }
    if (month == 8) {
        offset = 2;
    }
    if (month == 9 || month == 10) {
        offset = 3;
    }
    if (month == 11 || month == 12) {
        offset = 4;
    }
    return (month - 1) * 30 + offset + dayOfMonth;
}

void main() {
    make_window(800, 800);
    set_pen_color(color::red);
    set_pen_width(8);

// open file, read in data
    in.open("PORTLAND-OR.TXT");
    if (in.is_open()) {
        // read each column into an array
        for (int i = 0; i < 364; i++) {
            in >> yr[i] >> mo[i] >> day[i] >> windSpeed[i] >> precip[i] >> snowDepth[i] >> minTemp[i] >> maxTemp[i] >> avgTemp[i];
            int x_pos = daySinceJan(mo[i], day[i], yr[i]);
            int y_pos = avgTemp[i] * 2;
            draw_point(x_pos, y_pos);
        }
        in.close();
    }
    else {
        cout << "error reading file" << endl;
        exit(1);
    }
}

不仅仅是

UPDATE @t
SET XmlData.modify('insert <Material /> as first into (/Root/ProductDescription/Features)[1]')

然后它会工作