Sorry if this question sounds dumb and I am new to XML.
I have XML metadata that displays the Name of the table and all of its column names. In this example below, I want to read all 4 column names into 4 rows and also add table name to each iteration of the column name. But with what I tried, I could only partially achieve the output. It either displays one column name with it's respective table name or no table name but all the columns. Any suggestion is greatly appreciated. Thanks in advance!
So far I have tried to materialize a table and then read values using two methods. I would like to retrieve 4 rows and 2 columns (Table @Name, Field), here table name should repeat "CD_SAP_T000" for all four distinct column names.
Method #1:
DECLARE @xml XML = '<ROOT>
<Table Name="CD_SAP_T000">
<Field>CCCATEGORY</Field>
<Field>MANDT</Field>
<Field>MTEXT</Field>
<Field>ORT01</Field>
</Table>
</ROOT>'
SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) rowId,
x.Y.value('@Name[1]', 'VARCHAR(100)') AS TableName,
x.y.value('.', 'NVARCHAR(200)' ) AS ColumnName
FROM
@xml.nodes('//*[text()]') AS x(y)
Result for method #1:
rowId TableName ColumnName
--------------------------
1 NULL CCCATEGORY
2 NULL MANDT
3 NULL MTEXT
4 NULL ORT01
Method #2:
IF OBJECT_ID('dbo.myTable') IS NOT NULL
DROP TABLE dbo.myTable
CREATE TABLE [dbo].[myTable]
(
[Name] VARCHAR(100) NULL,
[Field] VARCHAR(100) NULL
);
DECLARE @Z_xml XML
SET @Z_xml = '<ROOT>
<Table Name="CD_SAP_T000">
<Field>CCCATEGORY</Field>
<Field>MANDT</Field>
<Field>MTEXT</Field>
<Field>ORT01</Field>
</Table>
</ROOT>'
INSERT INTO myTable (Name, Field)
SELECT
x.mytable.value('@Name[1]', 'VARCHAR(100)'),
x.mytable.value('Field[1]', 'VARCHAR(100)')
FROM
@Z_xml.nodes('//ROOT/Table') AS x ( mytable )
SELECT * FROM mytable
Result for method #2:
Name Field
--------------------------
CD_SAP_T000 CCCATEGORY