I have a xml which provides me table name with there respective ID column and column to update or insert on basis of those IDs below is the xml:
<tables>
<table>
<name>Table1</name>
<attr>
<id>1</id>
<columns>
<col_name>col1</col_name>
<col_val>123</col_val>
<columns>
<columns>
<col_name>col2</col_name>
<col_val>345</col_val>
<columns>
</attr>
<attr>
<id>2</id>
<columns>
<col_name>col3</col_name>
<col_val>123</col_val>
<columns>
</attr>
<attr>
<id>4</id>
<columns>
<col_name>col2</col_name>
<col_val>123</col_val>
<columns>
</attr>
</table>
<table>
<name>Table2</name>
<attr>
<id>1</id>
<columns>
<col_name>coltb1</col_name>
<col_val>123</col_val>
<columns>
<columns>
<col_name>coltb3</col_name>
<col_val>345</col_val>
<columns>
</attr>
<attr>
<id>3</id>
<columns>
<col_name>coltb4</col_name>
<col_val>123</col_val>
<columns>
</attr>
</table>
</tables>
In this I have table name which I can match with the table which is created in my db and on basis of ID column, I have to check whether the ID is present or not if present then I have to update the columns which are present in column node with the value and if not present I need to insert to the table.
Below is the code which I have done so far,
;WITH CTE (ID,TableName) As (SELECT ROW_NUMBER() OVER (ORDER BY CAST(y.item.query('data(name)') AS NVARCHAR(300))) AS ROWNUM,
CAST(y.item.query('data(name)') AS NVARCHAR(300)) AS TableName
FROM @input.nodes('/tables/table') y(item))
SELECT ID,TableName into #tmp FROM CTE
DECLARE @Counter INT,@tableName nvarchar(300)
SET @Counter=1
WHILE (@Counter<=(SELECT Count(*) FROM #tmp))
BEGIN
SET @tableName=(SELECT TableName FROM #tmp WHERE ID=@Counter)
;WITH CTE2(id) AS (SELECT CAST(x.item.query('data(id)') AS NVARCHAR(30)) AS id
FROM @input.nodes('/tables/table') y(item)
CROSS APPLY y.item.nodes('./attr') x(item)
WHERE CAST(y.item.query('data(name)') AS NVARCHAR(300))=@tableName)
SELECT * FROM CTE2
SET @Counter=@Counter+1
END
Here I am able to fetch the tablename and on looping of it I am getting the ID as well but , I am not able to find the column name and not getting how to do Merge on those column name as it is all dynamic.
Tables which I have in my db are
Table1:
ID|col1|col2|col3|col4|col5
---------------------------
1 |123 |345 |456 |null|89
2 |222 |444 |667 |890 |99
Table2
ID|coltb1|coltb2|coltb3|coltb4|coltb5
------------------------------------
1 |786 |678 |880 |99 |788
2 |345 |678 |667 |9990 |008
3 |344 |667 |623 |945 |678