I have the following query that generates the output
SELECT
top 1 AccountNumber as 'ExternalId' from Account
FOR XML PATH('Element'),type
--output generated
<Element>
<ExternalId>3002543105</ExternalId>
</Element>
How can I get the following output
<Element ClassName= "class1">
<ExternalId TYPE="String">3002543105</ExternalId>
</Element>
Thank you in advance
September 7, 2022 at 5:46 pm
Can you provide some sample data which we can test with?
The absence of evidence is not evidence of absence
- Martin Rees
The absence of consumable DDL, sample data and desired results is, however, evidence of the absence of my response
- Phil Parkin
September 7, 2022 at 5:53 pm
The data is just simple I have a table named Account that stores the account number
Table : Account
3002543105
3002543106
September 7, 2022 at 6:10 pm
Here is a dirty solution. Maybe there's a pretty solution out there that someone will come up with!
DROP TABLE IF EXISTS #Account;
CREATE TABLE #Account
(
AccountNumber VARCHAR(20) NOT NULL PRIMARY KEY CLUSTERED
);
INSERT #Account
(
AccountNumber
)
VALUES
('3002543105')
,('3002543106');
SELECT Res = CAST(REPLACE(
REPLACE(CAST(A.y AS VARCHAR(MAX)), '<Element>', '<Element ClassName="Class1">')
,'<ExternalId>'
,'<ExternalId TYPE="String">'
) AS XML)
FROM
(
SELECT ExternalId = a.AccountNumber
FROM #Account a
FOR XML PATH('Element'), TYPE
) A(y);
The absence of evidence is not evidence of absence
- Martin Rees
The absence of consumable DDL, sample data and desired results is, however, evidence of the absence of my response
- Phil Parkin
September 7, 2022 at 6:44 pm
There might be better ways, but I think Phil's solution looks good. Easy to enhance as well.
September 7, 2022 at 6:51 pm
I was playing around and I got the first part
SELECT
top 2 'class1' as [@ClassName]
,AccountNumber as 'ExternalId' from Account
FOR XML PATH('Element'),type
--generates output
<Element ClassName="class1">
<ExternalId>3002543105</ExternalId>
</Element>
<Element ClassName="class1">
<ExternalId>3002651195</ExternalId>
</Element>
But not sure how I add "TYPE" in <ExternalId> Tag.
September 7, 2022 at 7:37 pm
This, I think
SELECT 'Class1' AS "@ClassName",
'String' AS "ExternalId/@TYPE",
AccountNumber AS "ExternalId"
FROM #Account
FOR XML PATH('Element'),TYPE;
____________________________________________________
Deja View - The strange feeling that somewhere, sometime you've optimised this query before
How to get the best help on a forum
http://www.sqlservercentral.com/articles/Best+Practices/61537SELECT 'class1' AS [@ClassName]
, 'String' AS [ExternalId/@TYPE]
, a.AccountNumber AS ExternalId
FROM #Account AS a
FOR XML PATH('Element')
Drew
J. Drew Allen
Business Intelligence Analyst
Philadelphia, PA
September 7, 2022 at 9:08 pm
Thank you! That worked.
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply