sql >> Databasteknik >  >> RDS >> Sqlserver

SQL för att generera XML av tabelldata

Du kan använda information_schema.columns och for xml path så här för att få den struktur du vill ha.

select
  'MyTable' as 'TABLE/@name',
  (select XMLCol as '*'
   from (select XMLCol
         from MyTable
           cross apply
            (select
               COLUMN_NAME as 'COL/@name',
               case COLUMN_NAME when 'FirstName' then FirstName end as COL,
               case COLUMN_NAME when 'LastName' then LastName end as COL
             from INFORMATION_SCHEMA.COLUMNS
             where TABLE_NAME = 'MyTable'
             for xml path(''), root('ROW'), type) as Row(XMLCol)
        ) as Rows
   for xml path(''), type) as 'TABLE'
for xml path('')

Men i ditt fall ser jag inget annat alternativ än att bygga detta dynamiskt.

declare @TableName varchar(50) = 'MyTable'

declare @ColList varchar(8000)
select @ColList = coalesce(@ColList+', ', '') + 'case COLUMN_NAME when '''+COLUMN_NAME+''' then '+COLUMN_NAME+' end as COL'
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = @TableName

declare @SQL varchar(max) = 
'select
  ''_TABLENAME_'' as ''TABLE/@name'',
  (select XMLCol as ''*''
   from (select XMLCol
         from _TABLENAME_
           cross apply
            (select
               COLUMN_NAME as ''COL/@name'',
               _COLLIST_
             from INFORMATION_SCHEMA.COLUMNS
             where TABLE_NAME = ''_TABLENAME_''
             for xml path(''''), root(''ROW''), type) as Row(XMLCol)
        ) as Rows
   for xml path(''''), type) as ''TABLE''
for xml path('''')'

set @SQL = replace(@SQL, '_TABLENAME_', @TableName)
set @SQL = replace(@SQL, '_COLLIST_', @ColList)

exec (@SQL)


  1. Postgres-funktionen skapar men körs inte

  2. Kopiera en rad i samma tabell utan att behöva skriva de 50+ kolumnnamnen (medan du byter 2 kolumner)

  3. Hur man konverterar decimal till hexadecimal med TO_CHAR() i Oracle

  4. mysql autocasting sträng till heltal