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

Baca data XML ke dalam tabel hierarkis

Kita dapat (ab) menggunakan ROW_NUMBER() untuk menghasilkan ID di luar XQuery. Pembukaan:

WITH questions AS (
    SELECT
        ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS ID,
        n.q.value('(./questionText)[1]', 'nvarchar(max)') AS questionText,
        n.q.value('(./result)[1]', 'nvarchar(50)') AS result,
        n.q.query('answer') AS answers
    FROM
        @xml.nodes('/quizresult/question') AS n (q)
), questions_and_answers AS (
    SELECT ID, questionText, result, answer.query('.') AS answer
    FROM questions
    CROSS APPLY answers.nodes('answer') AS a(answer)
)

Dan sekarang ambil pertanyaan dengan

SELECT ID, questionText, result 
FROM questions

Dan jawabannya dengan

SELECT ID AS questionID,
    q.answer.value('answer[1]', 'nvarchar(max)') AS answer,
    q.answer.value('answer[1]/@number', 'int') AS number,
    q.answer.value('answer[1]/@value', 'int') AS val,
    q.answer.value('answer[1]/@chosen', 'bit') AS chosen
FROM questions_and_answers AS q


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Tutorial SQL (DDL, DML) pada contoh dialek MS SQL Server

  2. Menyiapkan dan Mengonfigurasi Replikasi SQL Server

  3. Bagaimana cara menerapkan pengeditan catatan Master/Detail?

  4. Sisipkan Pernyataan + Menggabungkan data tabel dan variabel dalam pemicu

  5. Memanggil Prosedur Tersimpan dengan XML Datatype