I am trying to export some of my SQL Server's table data to XML using the sp_MSforeachtable
clause. I could succeeded to an extent but stuck at adding TableName & Table Header as childs to the hierarchy.
What I have done so far,
DECLARE @TableNames nvarchar(max)
SELECT
@TableNames = STUFF((SELECT
',OBJECT_ID(''' + CONVERT(nvarchar(20), Name) + ''')'
FROM Sys.Tables
WHERE Name ='TableCustomers'
FOR xml PATH (''))
, 1
, 1
, '')
Print @TableNames
I am getting the output as,
OBJECT_ID('TableCustomers')
with this, I am running another query,
DECLARE @QueryForXMLs AS varchar(1000)
SET @QueryForXMLs = 'IF OBJECT_ID(''?'') IN (' + @TableNames + ')
Select * FROM ? FOR XML PATH(''Customer''), Root(''Customers'')'
Print @QueryForXMLs
EXEC sp_MSforeachtable @QueryForXMLs
With this I am getting the output as,
<Customers>
<Customer>
<Id>2</Id>
<CID>CU1</CID>
<Name>CuName</Name>
<Status>Active</Status>
</Customer>
</Customers>
This is working as expected if I have one row as an output for first query. But if I have multiple rows for the first query (WHERE Name Like'Table%'
instead of WHERE Name ='TableCustomers'
), I am getting the Root & Root Child name as hard-coded.
What would I be doing in order to get the dynamic table name and dynamic child name for each table execution using sp_MSforeachtable
I tried below approach but could not succeeded as the table name is coming along with schema name,
SET @QueryForXMLs = 'IF OBJECT_ID(''?'') IN (' + @TableNames + ')
Select * FROM ? FOR XML PATH(''Row''), Root(''?'')'