Search code examples
sql-serversql-server-2017sqlxml

How do I set a variable in an UPDATE statement, then use that variable in a xml.modify() statement?


Here is some demo data, and what I imagine the solution would look like:

CREATE TABLE #lookup_table (
    lookup_key VARCHAR(10),
    lookup_value VARCHAR(10)
);

INSERT INTO #lookup_table ( lookup_key, lookup_value )
    VALUES
        ( 'key1', 'value1' ),
        ( 'key2', 'value2' ),
        ( 'key3', 'value3' ),
        ( 'key4', 'value4' ),
        ( 'key5', 'value5' );

CREATE TABLE #dest_table (
    lookup_key VARCHAR(10),
    xml_data XML
);

INSERT INTO #dest_table (lookup_key, xml_data)
    VALUES
        ('key1', '<root><value /></root>'),
        ('key2', '<root><value /></root>'),
        ('key3', '<root><value /></root>'),
        ('key4', '<root><value /></root>'),
        ('key5', '<root><value /></root>')

-- Code in question --
DECLARE @value VARCHAR(10);

UPDATE #dest_table
SET @value = LT.lookup_value,
    xml_data.modify('insert text{sql:variable("@value")} into (./root/value)[1]')
FROM #dest_table DT
INNER JOIN #lookup_table LT
ON DT.lookup_key = LT.lookup_key;

SELECT * from #dest_table;

From my research this should work, but for some reason @value is always SET to NULL and the node is not updated:

lookup_key  xml_data
key1        <root><value /></root>
key2        <root><value /></root>
key3        <root><value /></root>
key4        <root><value /></root>
key5        <root><value /></root>

If I add an OUTPUT and follow the query with SELECT @value we see that the variable is indeed getting set -- the last entry in the table is displayed -- but OUTPUT is NULL:

DECLARE @value VARCHAR(10);

UPDATE #dest_table
SET @value = LT.lookup_value,
    xml_data.modify('insert text{sql:variable("@value")} into (./root/value)[1]')
OUTPUT @value
FROM #dest_table DT
INNER JOIN #lookup_table LT
ON DT.lookup_key = LT.lookup_key;

SELECT @value

Screenshot of SQL Server Management Studio output:

Screenshot of SQL Server Management Studio output


Solution

  • @GSerg offered an alternate solution which works perfectly -- elimintate the variable and use sql:column("LT.lookup_value") rather than sql:variable().

    UPDATE #dest_table
    SET xml_data.modify('insert text{sql:column("LT.lookup_value")} into (./root/value)[1]')
    FROM #dest_table DT
    INNER JOIN #lookup_table LT
    ON DT.lookup_key = LT.lookup_key;
    

    Assuming others are as well, I am still very interested to understand why the solution provided in the question does not work.