0

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(''?'')'
SharK
  • 2,155
  • 1
  • 20
  • 28
  • Is [this question](http://stackoverflow.com/a/39518959/5089204) an answer to your question? – Shnugo Oct 04 '16 at 10:37
  • @Shnugo. thanks for your message. Hmm not certainly as they are returning all with the name as 'AllTables' – SharK Oct 04 '16 at 13:25
  • So what is your expected output? What do you try to achieve? Please provide a sample in your question. – Shnugo Oct 04 '16 at 13:28

0 Answers0