将多个XML标签值放入带有逗号分隔符的单列中

时间:2020-03-18 21:45:15

标签: sql-server xml tsql sql-server-2017

我有一个XML,其中XML具有多个相似的标记,并且我希望此值需要用逗号分隔的一列显示并插入表中。

例如:

<test xmlns="http://www.google.com">
<code>a</code>
<code>b</code>
<code>c</code>
</test>

由于XML太大,我正在使用OPENXML来执行操作并将该值插入到特定表中。

我的表现像

insert into table A
(
    code
)
select Code from OPENXML(sometag)
with (
    code varchar(100) 'tagvalue'
)

对于XQUERY,我使用的是这样的内容:'for $i in x:Code return concat($i/text()[1], ";")',我也想对OPENXML使用。

输出:我想将代码标记值放入a,b,c或a / b / c等一列。

3 个答案:

答案 0 :(得分:2)

由于您使用的是SQL Server 2017,因此可以使用STRING_AGG (Transact-SQL)来连接代码值,例如:

create table dbo.Test (
  someTag xml
);

insert dbo.Test (someTag) values
  ('<test><code>a</code><code>b</code><code>c</code></test>'),
  ('<test><code>d</code><code>e</code><code>f</code></test>');

select [Code], [someTag]
from dbo.Test
outer apply (
  select [Code] = string_agg([value], N',')
  from (
    select n1.c1.value('.', 'nvarchar(100)')
    from someTag.nodes(N'/test/code') n1(c1)
  ) src (value)
) a1;

哪个产量...

Code    someTag
a,b,c   <test><code>a</code><code>b</code><code>c</code></test>
d,e,f   <test><code>d</code><code>e</code><code>f</code></test>

答案 1 :(得分:1)

只需稍作调整即可始终学习(+1)

示例

Declare @YourTable table (ID int,XMLData xml)
insert Into @YourTable values
(1,'<test><code>a</code><code>b</code><code>c</code></test>')

Select A.ID
      ,B.*
 From @YourTable A
 Cross Apply (
               Select DelimString = string_agg(xAttr.value('.','varchar(max)'),',')
                From  A.XMLData.nodes('/test/*') xNode(xAttr)
             ) B

返回

ID  DelimString
1   a,b,c

答案 2 :(得分:0)

为了完整起见,这是通过纯XQuery和FLWOR表达式进行的方法3。

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, xmldata xml);

INSERT @tbl (xmldata) VALUES
('<test  xmlns="http://www.google.com"><code>a</code><code>b</code><code>c</code></test>'),
('<test  xmlns="http://www.google.com"><code>d</code><code>e</code><code>f</code></test>');
-- DDL and sample data population, end

DECLARE @separator CHAR(1) = ',';

-- Method #3
-- SQL Server 2005 onwards
;WITH XMLNAMESPACES (DEFAULT 'http://www.google.com')
SELECT ID
   , xmldata.query('for $i in /test/code
      return if ($i is (/test/code[last()])[1]) then string($i)
            else concat($i, sql:variable("@separator"))')
   .value('.', 'NVARCHAR(MAX)') AS [Comma_separated_list]
FROM @tbl;

输出

+----+----------------------+
| ID | Comma_separated_list |
+----+----------------------+
|  1 | a, b, c              |
|  2 | d, e, f              |
+----+----------------------+
相关问题