1

是否可以使用 SQL Server 2012MERGE从 XML 流更新表中的多个记录?

我的表如下:

在此处输入图像描述

我每天几次收到以下 XML 信封:

<WeatherForecastUpdate>
    <Location Temperature="67" Id="56">
        <Humidity>78%</Humidity>
        <Condition>Rain</Condition>
        <Wind>5mph</Wind>
    </Location>
    <Location Temperature="72" Id="783">
        <Humidity>51%</Humidity>
        <Condition>Clear</Condition>
        <Wind>5mph</Wind>   
    </Location>
</WeatherForecastUpdate>

我需要根据LocationIDXML 更新天气数据。我知道如何处理MERGE每条消息(位置),但我想知道是否有办法更新单个MERGE.

4

1 回答 1

2

是的你可以!首先将 xml 转换为表,然后 MERGE:

DECLARE @x xml = N'<WeatherForecastUpdate>
    <Location Temperature="67" Id="56">
        <Humidity>78%</Humidity>
        <Condition>Rain</Condition>
        <Wind>5mph</Wind>
    </Location>
    <Location Temperature="72" Id="783">
        <Humidity>51%</Humidity>
        <Condition>Clear</Condition>
        <Wind>5mph</Wind>   
    </Location>
</WeatherForecastUpdate>'

;WITH cte AS (
    SELECT  t.v.value('@Temperature','int') Temperature,
            t.v.value('@Id','int') Id,
            t.v.value('(./Humidity)[1]','nvarchar(5)') Humidity,
            t.v.value('(./Condition)[1]','nvarchar(10)') Condition,
            t.v.value('(./Wind)[1]','nvarchar(10)') Wind
    FROM @x.nodes('/WeatherForecastUpdate/Location') as t(v)
)

MERGE YourTable as t
USING cte as s
ON t.LocationID = s.ID
WHEN MATCHED THEN
    UPDATE SET  Temp = s.Temperature,
                Humidity = s.Humidity,
                Wind = s.Wind

另一种使用简单更新的方法:

UPDATE t
SET Temp = s.Temperature,
    Humidity = s.Humidity,
    Wind = s.Wind
FROM YourTable t
INNER JOIN cte s
    ON t.LocationID = s.ID
于 2016-09-03T03:49:21.570 回答