I have below typed xml
<root>
<row1 invoice_number="WEDRT" vendor="Telekm" amount="233" status="1" created_date="42590" />
<row2 invoice_number="MSFDRT" vendor="ARS" amount="344" status="1" created_date="42955" />
</root>
This xml is generated dynamically. By dynamic I mean at the time of writing the sql code to parse it I don't know how many rows and attributes would be there. There could be as many rows as 100,000 and as many attributes as user wants. I won't even know the name of the attributes.
Is it possible to put it in a temp table by producing following type of result out of this xml?
Invoice_number Vendor amount status created_Date
WEDRT TELEKOM 233 1 42590
MSFDRT ARS 344 1 42955
I have tried the following
DECLARE
@xml XML,
@Columns VARCHAR(MAX)
SET @xml = '
<root>
<row1 invoice_number="WEDRT" vendor="Telekm" amount="233" status="1" created_date="42590" />
<row2 invoice_number="MSFDRT" vendor="ARS" amount="344" status="1" created_date="42955" />
</root>
'
BEGIN
SET NOCOUNT ON;
DECLARE @COUNT INT, @COUNTER INT, @TQUERY VARCHAR(2000), @SELECT VARCHAR(MAX), @VALUES VARCHAR(MAX)
SELECT * INTO #TEMPTABLE
FROM(
SELECT
CAST(x.v.query('local-name(.)') AS VARCHAR(100)) As AttributeName,
v.value('.' , 'VARCHAR(100)') AS Value
FROM @XML.nodes('//@*') x(v)
) A
SELECT * FROM #TEMPTABLE
DROP TABLE #TEMPTABLE
END
It gives me result like below table for 2 rows in xml
AttributeName Value
invoice_number WEDRT
vendor Telekom
amount 233
status 1
created_Date 42590
invoice_number MSFDRT
vendor ARS
amount 344
status 1
created_Date 42955