Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

SQL untuk menghasilkan XML data tabel

Anda dapat menggunakan information_schema.columns dan for xml path seperti ini untuk mendapatkan struktur yang Anda inginkan.

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('')

Tetapi dalam kasus Anda, saya tidak melihat pilihan lain selain membangun ini secara dinamis.

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Log Transaksi SQL Server, Bagian 1:Dasar-dasar Pencatatan

  2. Cara mengubah data dari baris berdasarkan kolom tertentu ke struktur data lain

  3. Cara Menggunakan Fitur SQL Server AlwaysOn

  4. Bagaimana secara otomatis menambahkan tanggal 1 tahun ke tanggal yang ada di SQL Server

  5. Mengoptimalkan TempDB:Menghindari Kemacetan dan Masalah Kinerja