简体   繁体   中英

Select SQL Query to get xml node values from ntext column?

I want to get one xml node value from NTEXT column which contains xml based on where clause quering on another xml node value. RDBMS Type: Microsoft SQL Server T-SQL Here: I want to get Code node value based on StoreId where clause value. How do I get it? Input: 100 Output:ABCDE

For example:

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

If you are using SQL Server 2005 or 2008 you can use XQuery like so:

For more on XQuery see 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM