简体   繁体   中英

How to extract values from a XML column in SQL and insert into new columns?

I have a table which has a column which is a XML column. I can use this to get some values from the xml:

Select TOP 10 
    mq.Id
    , m.c.value('.', 'varchar(64)') as VisitId
    , n.c.value('.', 'varchar(64)') as VisitorId
    , p.c.value('.', 'varchar(64)') as SearchId
from [Message] as mq
    outer apply mq.ActivityLoggingData.nodes('ActivityLoggingData/VisitId') as m(c)
    outer apply mq.ActivityLoggingData.nodes('ActivityLoggingData/VisitorId') as n(c)
    outer apply mq.ActivityLoggingData.nodes('ActivityLoggingData/SearchId') as p(c)

The xml is similar to:

<ActivityLoggingData xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <VisitId>c751de63-1305-4a5a-903e-677b5923d2c2</VisitId>
  <VisitorId>750b76eb-4727-4eb1-9737-cc7ce206e56b</VisitorId>
  <SearchId>baef33dc-8827-42a5-b2bd-a60ffe71aea8</SearchId>
  ...
</ActivityLoggingData>

Now, I added columns in table [Message]: VisitId, VisitorId and SearchId.

My question is: how can I extract these values from the xml column AND insert into these new columns? table Message has an Id column, we can use it and insert these values into temp table first, then update the [Message]. But, is there a way to do it without using temp table?

The database is SQL Server.

Thanks

Please check this out.

DECLARE @xmldata XML = N'<ActivityLoggingData xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <VisitId>c751de63-1305-4a5a-903e-677b5923d2c2</VisitId>
  <VisitorId>750b76eb-4727-4eb1-9737-cc7ce206e56b</VisitorId>
  <SearchId>baef33dc-8827-42a5-b2bd-a60ffe71aea8</SearchId>
</ActivityLoggingData>'

DECLARE @T TABLE(VisitId nvarchar(50), VisitorId nvarchar(50), SearchId nvarchar(50))

INSERT INTO @T(VisitId, VisitorId, SearchId)
SELECT x.value(N'(VisitId)[1]', N'nvarchar(50)'),
       x.value(N'(VisitorId)[1]', N'nvarchar(50)'),
       x.value(N'(SearchId)[1]', N'nvarchar(50)')
  FROM @xmldata.nodes(N'/ActivityLoggingData') AS XTbl(x)

SELECT * 
  FROM @T

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