如何选择以逗号分隔并使用自定义格式(例如:x)
进行装饰的XML列表值输入样本,它将有多行
1 | <User Name="AAA" /><User Name="BBB" />
2 | <User Name="CCC" /><User Name="DD" />
需要输出
1 | xAAAx,xBBBx
2 | xCCCx,xDDDx
我的进步
DECLARE @xml XML
SELECT @xml = N'
<User Name="AAA"/>
<User Name="BBB"/>'
Declare @TempT TABLE (id int, data xml)
INSERT INTO @TempT VALUES (1,@xml)
set @xml = N'
<User Name="CCC"/>
<User Name="DDD"/>'
INSERT INTO @TempT VALUES (2,@xml)
SELECT * from @TempT
DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+', ' ,'')
+ 'x'+T.C.value('@Name', 'nvarchar(50)') +'x'
FROM @xml.nodes('User') T(C)
SELECT @listStr
答案 0 :(得分:1)
declare @TempT table(data xml)
insert into @TempT (data) values
(N'<User Name="AAA"/><User Name="BBB"/><User Name="CCC"/>'),
(N'<User Name="CCC"/><User Name="DDD"/>');
select stuff((
select ',x'+N.X.value('.', 'nvarchar(50)')+'x'
from T.data.nodes('/User/@Name') as N(X)
for xml path(''), type
).value('text()[1]', 'nvarchar(max)'), 1, 1, '')
from @TempT as T;
结果:
-------------------
xAAAx,xBBBx,xCCCx
xCCCx,xDDDx
答案 1 :(得分:0)
Declare @TempT TABLE (id int, data xml) insert into @TempT values (1, N'<User Name="AAA"/><User Name="BBB"/>'); insert into @TempT values (2, N'<User Name="CCC"/><User Name="DDD"/>'); SELECT * from @TempT; select 'x' + data.value('(User/@Name)[1]', 'varchar(50)') + 'x,' + 'x' + data.value('(User/@Name)[2]', 'varchar(50)') + 'x' from @TempT GO
id | data -: | :------------------------------------- 1 | <User Name="AAA" /><User Name="BBB" /> 2 | <User Name="CCC" /><User Name="DDD" /> | (No column name) | | :--------------- | | xAAAx,xBBBx | | xCCCx,xDDDx |
dbfiddle here