2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SQL Severでxml列のデータを扱う時用メモ

Posted at

SQL Serverでxmlを扱いたいときにはxqueryを使う必要がある。
変数ではなく、xml列にデータが入っている際の扱いに関して、たまに使うときにわすれてしまうのでメモ

■Bulk InsertするときのCSVの中身
※当たり前だけど、xml列に対してxqueryを投げるために、Bulk Insertするときはxml列のデータ形式は「xml」を指定する必要がある(vacharとかじゃだめ)

id,xml
2,<root><item id="1">1</item><item id="3">2</item><item id="2">3</item><item id="5">4</item></root>
3,<root><item id="1">1</item><item id="4">2</item><item id="2">3</item><item id="6">4</item></root>

■Bulk Insterのためのクエリ

CREATE TABLE src (
  id varchar(33),
  xml xml NULL
);

BULK INSERT src
FROM 'ファイルパス'
WITH
(
   DATAFILETYPE='char',
   FIRSTROW=2,
   FIELDTERMINATOR = ',',
   ROWTERMINATOR = '0x0a'
);

■テーブルの中身

Kobito.0Kkk2c.png

■xml列の中身

<root>
  <item id="1">1</item>
  <item id="3">2</item>
  <item id="2">3</item>
  <item id="5">4</item>
</root>

■取得するためのクエリ

select
	id,
    t.item.query('.') as Item,
    t.item.value('@id','char(50)') as id,
    t.item.value('.','char(50)') as content
from src
cross apply xml.nodes('/root/item') as t(item);

■取得内容

Kobito.uBbUUz.png

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?