snippetsqlMinor
How can I position the element generated by XMLTEXT in a FOR XML query?
Viewed 0 times
canthegeneratedquerypositionxmlelementforhowxmltext
Problem
I'm trying to use
My XML needs to look like this; for every record in the database,
When I use the following query, the `
INSERT INTO #temp VALUES (1), (2);
SELECT
1 AS Tag,
NULL AS Parent,
id AS [entry!1!id!ELEMENT],
''
AS [entry!1!test!XMLTEXT]
-- other columns
FROM #temp
FOR XML EXPLICIT;
DROP TABLE #temp;
1
FOR XML to simulate an OData feed. One of the requirements I have is that somewhere I need an XML element which is constant for all records; I was planning to use the XMLTEXT directive for this.My XML needs to look like this; for every record in the database,
1
When I use the following query, the `
element appears before the element, even though the declaration appears after it:
CREATE TABLE #temp (id int);INSERT INTO #temp VALUES (1), (2);
SELECT
1 AS Tag,
NULL AS Parent,
id AS [entry!1!id!ELEMENT],
''
AS [entry!1!test!XMLTEXT]
-- other columns
FROM #temp
FOR XML EXPLICIT;
DROP TABLE #temp;
This gives the following results (fiddle):
1
Am I doing something wrong here, or is this a limitation of XMLTEXT? A workaround might be to treat it as a regular nested element, but would that work even though I have more nested elements further down in the ` element?Solution
After some more fiddling, I found out that there is an XML directive which does the job (if I omit the attribute name,
This produces the results I want:
(demo)
This directive is mentioned briefly here but I couldn't find more documentation or any examples.
test): SELECT
1 AS Tag,
NULL AS Parent,
id AS [entry!1!id!ELEMENT],
''
AS [entry!1!!XML]
FROM #temp
FOR XML EXPLICIT;This produces the results I want:
1
(demo)
This directive is mentioned briefly here but I couldn't find more documentation or any examples.
Code Snippets
SELECT
1 AS Tag,
NULL AS Parent,
id AS [entry!1!id!ELEMENT],
'<test type="dummy" />'
AS [entry!1!!XML]
FROM #temp
FOR XML EXPLICIT;Context
StackExchange Database Administrators Q#229590, answer score: 2
Revisions (0)
No revisions yet.