简体   繁体   中英

How to replace a pointer value with a variable in sql xml?

I need to write a WHILE loop and pass a variable to an xml query:

Given this logic:

DECLARE @count INT = 0;
DECLARE @pointer INT = 0;
DECLARE @pointer_str varchar(100);

DECLARE @MyXML XML
SET @MyXML = '<SampleXML>
                <Colors>
                <Color1>White</Color1>
                <Color2>Blue</Color2>
                <Color3>Black</Color3>
                <Color4 Special="Light">Green</Color4>
                <Color5>Red</Color5>
                </Colors>
                <Colors>
                <Color1>White</Color1>
                <Color2>Blue</Color2>
                <Color3>Black</Color3>
                <Color4 Special="Light">Green</Color4>
                <Color5>Red</Color5>
                </Colors>
            </SampleXML>'

SET @count = 
    (
        SELECT
            a.b.value('count(/SampleXML/Colors)', 'int')
        FROM 
            @MyXML.nodes('data') a(b)
    )

WHILE @count < @pointer
    BEGIN   
        SELECT
            a.b.value('Colors[' + @pointer + ']/Color1[1]','varchar(10)') AS Color1
        FROM 
            @MyXML.nodes('SampleXML') a(b);

        SELECT @pointer = @pointer + 1;
    END 

I am trying to get the following variable in a SELECT statement to parse XML but I receive the following error:

The argument 1 of the XML data type method "value" must be a string literal.

Also, when I pass it the literal value of '1', I can't see the select being run inside the loop. can someone please help me?

I need to write a WHILE loop and pass a variable to an xml query:

In XML.value() method, you can refer to a variable varName as sql:variable("@varName") .

Regarding your question, it appeard to me that you are trying extract the text within Color1 nodes in your XML. The following SQL does that:

DECLARE @count INT = 0;
DECLARE @pointer INT = 0;
DECLARE @pointer_str varchar(100);

DECLARE @MyXML XML
SET @MyXML = '<SampleXML>
        <Colors>
        <Color1>White</Color1>
        <Color2>Blue</Color2>
        <Color3>Black</Color3>
        <Color4 Special="Light">Green</Color4>
        <Color5>Red</Color5>
        </Colors>
        <Colors>
        <Color1>Green</Color1>
        <Color2>Blue</Color2>
        <Color3>Black</Color3>
        <Color4 Special="Light">Green</Color4>
        <Color5>Red</Color5>
        </Colors>
    </SampleXML>'

SELECT @count = count(a.b.query('.')) FROM @MyXml.nodes('/SampleXML/Colors') as a(b)

SELECT
    a.b.value('.', 'varchar(10)')
FROM 
    @MyXML.nodes('/SampleXML/Colors/Color1') a(b);

It produces the output as

----------
White
Green

(2 row(s) affected)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM