Imagine I have some XML that looks like this:
DECLARE @xml XML
SET @xml = CAST(N'<row><id>1</id><a>b</a></row><row><id>2</id><a>x</a></row>' AS XML)
That is:
<row>
<id>1</id>
<a>b</a>
</row>
<row>
<id>2</id>
<a>x</a>
</row>
The id element is the key of each row, and it may be dynamic, so I have it stored in a variable:
DECLARE @idname NVARCHAR(MAX)
SET @idname = N'id'
I would like to have a resultset with two columns, the id value and the row’s contents.
I tried this:
SELECT node.value(N'xxx', N'NVARCHAR(MAX)') AS key, CAST(node.query(N'.') AS NVARCHAR(MAX)) AS value
FROM @xml.nodes(N'/row') AS roots(node)
The problem is, I don’t know what to put inside value, instead of xxx. I would like to be able to do something like:
node.value(@idname, N'VARCHAR(MAX))
So that my variable would be evaluated as an XPath expression, but I know it’s not possible. If I use instead:
node.value(N'sql:variable("@idname")', N'NVARCHAR(MAX)')
It will return the value that’s in the @idname variable, instead of evaluating it.
What I want to have is:
--------------------------------------
key |value
--------------------------------------
1 |<id>1</id><a>b</a>
2 |<id>2</id><a>x</a>
So, is this possible at all?
Thanks!
1 Answer