在我的数据库中的一个表中,我有一个列,其中整个条目是一个长XML字符串,具有以下结构:
<Group1>
<Title>
<Name>John Doe</Name>
<Phone>555-3421</Phone>
<Email>catman@gmail.com</Email>
(+more)
</Title>
</Group1>
这是我的SELECT语句,这是它输出的内容:
SELECT TheKey, TheData FROM MyTable;
SQL Server Management Studio中的输出:
TheKey TheData
10000 <Group1><Title><Name>John Doe</Name><Phone>893-3421</Phone><Email>catman@gmail.com</Email></Title></Group1>
10001 <Group1><Title><Name>Mary Sue</Name><Phone>381-2342</Phone><Email>thebestdude@gmail.com</Email></Title></Group1>
10002 <Group1><Title><Name>Mark Dark</Name><Phone>312-7626</Phone><Email>mybook231@gmail.com</Email></Title></Group1>
10003 <Group1><Title><Name>Garth Dan</Name><Phone>341-4572</Phone><Email>lampshade032@gmail.com</Email><State>California</State></Title></Group1>
我想写一些MS SQL查询,它会将这样的数据返回给我:
TheKey Name Phone Email State
10000 John Doe 893-3421 catman@gmail.com NULL
10001 Mary Sue 381-2342 thebestdude@gmail.com NULL
10002 Mark Dark 312-7626 mybook231@gmail.com NULL
10003 Garth Dan 341-4572 lampshade032@gmail.com California
注意最后一个条目如何有一个额外的XML标记<State>
,其他条目没有。我希望它像这样灵活 - 使用某种父/子引用?
任何帮助这样做都会非常感激,我似乎无法在任何地方找到类似的东西=)
答案 0 :(得分:8)
如果您的XML列存储为XML类型,那么您可以使用XPath查询来获取每列。像这样:
SELECT TheKey,
TheData.value('(/Group1/Title/Name)[1]', 'varchar(100)') AS Name,
TheData.value('(/Group1/Title/Phone)[1]', 'varchar(100)') AS Phone,
TheData.value('(/Group1/Title/Email)[1]', 'varchar(250)') AS Email,
TheData.value('(/Group1/Title/State)[1]', 'varchar(100)') AS [State]
FROM MyTable
如果列MyData
是varchar而不是XML,那么您可以在查询期间强制转换它。像这样:
SELECT TheKey,
Cast(TheData AS XML).value('(/Group1/Title/Name)[1]', 'varchar(100)') AS Name,
Cast(TheData AS XML).value('(/Group1/Title/Phone)[1]', 'varchar(100)') AS Phone,
Cast(TheData AS XML).value('(/Group1/Title/Email)[1]', 'varchar(250)') AS Email,
Cast(TheData AS XML).value('(/Group1/Title/State)[1]', 'varchar(100)') AS [State]
FROM MyTable
是的,我从其他SO文章中得到了这些信息。 (投票让其他人更容易找到它)How to query xml column in tsql
答案 1 :(得分:-1)
--OBTAIN THE XML DATA
declare @xml as xml = '
<division>
<linea>
<id_division>01</id_division>
<division>REPUESTOS</division>
</linea>
<linea>
<id_division>02</id_division>
<division>BATERIAS</division>
</linea>
<linea>
<id_division>03</id_division>
<division>LUBRICANTES</division>
</linea>
<linea>
<id_division>04</id_division>
<division>NEUMATICOS</division>
</linea>
</division>'
-- create table or you can use existing table for structure
create table #tmp_table (
id_division integer,
division nvarchar(20)
)
declare @docHandle int
EXEC sp_xml_preparedocument @docHandle OUTPUT, @xml;
SELECT *
FROM OPENXML(@docHandle, '/division/linea',3)
WITH #tmp_table;
---DELETE tmp_TABLE
drop table #tmp_table