选择SQL Query从ntext列获取xml节点值?

时间:2011-09-12 21:36:17

标签: sql sql-server xml xpath

我想从NTEXT列获取一个xml节点值,该列包含基于where子句查询另一个xml节点值的xml。 RDBMS类型:Microsoft SQL Server T-SQL 这里:我想根据StoreId where子句值获取Code节点值。我怎么得到它? 输入:100 输出:ABCDE

例如:

<root>
  <StoreProfile>
    <General>
     <StoreId>100</StoreId>
     <Code>ABCDE</Code>
    </General>
  </StoreProfile>
</root>

1 个答案:

答案 0 :(得分:6)

如果您使用的是SQL Server 2005或2008,则可以像这样使用XQuery:

有关XQuery的更多信息,请参阅XQuery Language Reference

DECLARE @storeId INT
SET @storeId = 100

CREATE TABLE #TestTable
(
    xmlColumn NTEXT
)

INSERT INTO #TestTable (xmlColumn) Values('<root><StoreProfile><General><StoreId>100</StoreId><Code>ABCDE</Code></General></StoreProfile></root>')
INSERT INTO #TestTable (xmlColumn) Values('<root><StoreProfile><General><StoreId>200</StoreId><Code>FGHIJ</Code></General></StoreProfile></root>')

SELECT 
    StoreProfile.value('Code[1]', 'nvarchar(10)') as Code 
FROM #TestTable
    CROSS APPLY (SELECT CAST(xmlColumn AS XML)) AS A(B) 
    CROSS APPLY A.B.nodes('//root/StoreProfile/General[StoreId = sql:variable("@storeId")]') AS StoreProfiles(StoreProfile)

DROP TABLE #TestTable