简体   繁体   English

如何从 SQL 中的 XML 列中提取值并插入新列?

[英]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.我有一个表,其中有一列是 XML 列。 I can use this to get some values from the xml:我可以使用它从 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: xml 类似于:

<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.现在,我在表 [Message] 中添加了列:VisitId、VisitorId 和 SearchId。

My question is: how can I extract these values from the xml column AND insert into these new columns?我的问题是:如何从 xml 列中提取这些值并插入到这些新列中? table Message has an Id column, we can use it and insert these values into temp table first, then update the [Message]. table Message 有一个 Id 列,我们可以使用它并将这些值先插入到 temp 表中,然后更新 [Message]。 But, is there a way to do it without using temp table?但是,有没有办法在不使用临时表的情况下做到这一点?

The database is SQL Server.数据库是 SQL 服务器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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