sql-server - 将 XML 数据插入到表中
问题描述
我需要将外部 XML 文件数据插入到 SQL Server 表中。我尝试了下面的代码。但这会插入一条记录,其中NULL
包含所有列的值
Declare @xml XML
Select @xml =
CONVERT(XML,bulkcolumn,2) FROM OPENROWSET(BULK
'C:\Users\PC901\Downloads\Tags.xml',SINGLE_BLOB) AS X
SET ARITHABORT ON
TRUNCATE TABLE Tags
Insert into Tags
(
ID,WikiPostId,ExcerptPostId,Count,TagName
)
Select
P.value('ID[1]','BIGINT') AS ID,
P.value('WikiPostId[1]','BIGINT') AS WikiPostId,
P.value('ExcerptPostId[1]','BIGINT') AS ExcerptPostId,
P.value('Count[1]','BIGINT') AS Count,
P.value('TagName[1]','VARCHAR(100)') AS TagName
From @xml.nodes('/tags') PropertyFeed(P)
SELECT * FROM Tags
并且示例 XML 将是
<?xml version="1.0" encoding="utf-8"?>
<tags>
<row Id="1" TagName=".net" Count="283778" ExcerptPostId="3624959" WikiPostId="3607476" />
<row Id="2" TagName="html" Count="826083" ExcerptPostId="3673183" WikiPostId="3673182" />
<row Id="3" TagName="javascript" Count="1817846" ExcerptPostId="3624960" WikiPostId="3607052" />
<row Id="4" TagName="css" Count="588062" ExcerptPostId="3644670" WikiPostId="3644669" />
<row Id="5" TagName="php" Count="1286873" ExcerptPostId="3624936" WikiPostId="3607050" />
</tags>
解决方案
干得好:
declare @xml xml = '<?xml version="1.0" encoding="utf-8"?>
<tags>
<row Id="1" TagName=".net" Count="283778" ExcerptPostId="3624959" WikiPostId="3607476" />
<row Id="2" TagName="html" Count="826083" ExcerptPostId="3673183" WikiPostId="3673182" />
<row Id="3" TagName="javascript" Count="1817846" ExcerptPostId="3624960" WikiPostId="3607052" />
<row Id="4" TagName="css" Count="588062" ExcerptPostId="3644670" WikiPostId="3644669" />
<row Id="5" TagName="php" Count="1286873" ExcerptPostId="3624936" WikiPostId="3607050" />
</tags>'
Select
P.value('@Id','BIGINT') AS ID,
P.value('@WikiPostId','BIGINT') AS WikiPostId,
P.value('@ExcerptPostId','BIGINT') AS ExcerptPostId,
P.value('@Count','BIGINT') AS Count,
P.value('@TagName','VARCHAR(100)') AS TagName
From @xml.nodes('/tags/row') PropertyFeed(P)
输出
ID WikiPostId ExcerptPostId Count TagName
----------- -------------------- -------------------- -------------------- ----------
1 3607476 3624959 283778 .net
2 3673182 3673183 826083 html
3 3607052 3624960 1817846 javascript
4 3644669 3644670 588062 css
5 3607050 3624936 1286873 php
(5 rows affected)
推荐阅读
- c# - DatePicker 总是在详细信息页面中重置为今天的日期
- reactjs - 将现有项目添加到购物车 (React-Redux)
- python - 将条目添加到 Pandas 数据框作为列而不是行
- batch-file - 创建具有登录、注册和身份验证功能的 BATCH 文件
- c# - .Net core 3.1 中接受的各种 application/json Content-type
- docker - docker镜像之间的常用命令
- sendgrid - SendGrid 中的动态模板:检查字符串
- java - 尝试在 c:\Users\"firstname" "lastname" 中使用 vscode for Java Space 导致错误
- spring-boot - 骆驼上下文根本没有在 Hawtio JMX 中列出
- networking - aws ec2 实例的 Ubuntu 18.04 netplan 配置