简体   繁体   中英

SQL Server parse a column's XML value into a table (for each row)

Sorry if the topic isn't very clear, but here is what I need to accomplish. I have a table like so:

 user_id   | friends
==============================
75          | <friend name="bob" /><friend name="joe" />
76          | <friend name="bill" /><friend name="bob" />
77          | <friend name="sam" /><friend name="gary" /><friend name="john" />

I need to get the number of friends (ie, number of XML nodes) for each user. The resulting table should look like this:

 user_id   | number_of_friends
==============================
75         | 2
76         | 2
77         | 3

The following SQL can do it for one column at a time, but I'm not sure how to do it for all columns in one go.

DECLARE @x XML;

SELECT @x = pval 
FROM [mytable]
WHERE uid=75 AND pkey='roster';

SELECT COUNT(t.c.value('@name', 'NVARCHAR(MAX)')) AS number_of_friends
FROM @x.nodes('//friend') t(c);

This results in the table:

number_of_friends
=================
2

If it is SQL Server you can use XQuery count function:

SELECT  [user_id],
        friends.value('count(/friend)','integer') as number_of_friends
FROM YourTable

In MySQL - ExtractValue() :

SELECT  `user_id`,
        ExtractValue(`friends`, 'count(/friend)')
FROM `YourTable`

You can try this trick: Remove (replace) what you are searching for and compare the difference in string length:

SELECT 
    user_id,    
    ROUND (
        (
            LENGTH(friends)
            - LENGTH( REPLACE ( friends, "<friend", "") ) 
        ) / LENGTH("<friend")        
    ) AS count  
FROM friendtable 

Running fiddle

Count the number of occurrences of a string in a VARCHAR field?

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