我正忙于将一个网站从基于 xml 的文件转换为 SQL Server 2012 express 数据库,现在我已经设法从 xml 中获取大部分标签以轻松导入到 SQL Server 中
我现在的问题在于这些 xml 的特定部分
这是我遇到问题的部分
<?xml version="1.0" encoding="utf-16"?>
<License xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Reference>00b2d4cf-699c-4427-bcf0-a0ca456654c2</Reference>
<MacAddresses>
<string>00:0D:87:FE:9A:21</string>
<string>00:20:ED:14:47:64</string>
<string>00:13:D3:11:7C:D2</string>
<string>00:13:D3:11:7C:D8</string>
<string>00:19:D1:04:12:98</string>
<string>00:19:66:C0:7F:AF</string>
</MacAddresses>
</License>
我有每个许可证的引用以及分配给该许可证的 MAC 地址。
现在我希望它按如下方式将其导入到 sql 中:
Reference MACAddress
--------- ----------
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:0D:87:FE:9A:21
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:20:ED:14:47:64
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:13:D3:11:7C:D2
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:13:D3:11:7C:D8
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:19:D1:04:12:98
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:19:D1:04:12:98
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:19:66:C0:7F:AF
我会手动完成,但我有 700 多个导入许可证,手动完成会花费太长时间。
帮助将不胜感激
最佳答案
如果您使用的是 SQL Server 2005 或更新版本,您可以使用 native XQuery 支持从 XML 中提取您想要的数据:
DECLARE @input XML = '<License xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Reference>00b2d4cf-699c-4427-bcf0-a0ca456654c2</Reference>
<MacAddresses>
<string>00:0D:87:FE:9A:21</string>
<string>00:20:ED:14:47:64</string>
<string>00:13:D3:11:7C:D2</string>
<string>00:13:D3:11:7C:D8</string>
<string>00:19:D1:04:12:98</string>
<string>00:19:66:C0:7F:AF</string>
</MacAddresses>
</License>'
SELECT
Reference = License.value('(Reference)[1]', 'varchar(50)'),
MacAddress = MacAddr.value('.', 'varchar(50)')
FROM
@input.nodes('License') AS XTbl1(License)
CROSS APPLY
License.nodes('MacAddresses/string') AS XTbl2(MacAddr)
给出输出:
Reference MacAddress
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:0D:87:FE:9A:21
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:20:ED:14:47:64
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:13:D3:11:7C:D2
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:13:D3:11:7C:D8
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:19:D1:04:12:98
00b2d4cf-699c-4427-bcf0-a0ca456654c2 00:19:66:C0:7F:AF
当然,您也可以在 SELECT
之前使用 INSERT INTO dbo.YourTable(Reference, MacAddress) ....
自动将此数据插入到表格
关于sql - 从 xml 文件向 SQL Server 数据库添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16653540/