SQL Server 2012开发人员版
TESTMACHINE :
OID MACHINENAME
---------------
1 TEST A
2 TEST B
3 TEST C
TESTDETAIL :
OID TESTMACHINEOID TESTID HISTORYID
-------------------------------------
1 1 200 100
2 1 300 250
3 2 1000 2345
4 3 100 150
TestMachineOID
是TestMachine
表
我需要通过对TestMachineOID
进行分组来将项目连接成XML。是否有可能获得以下所需的输出?
TESTMACHINEOID TESTMACHINENAME TEXTXML
------------------------------------------------------------------------
1 TEST A <REC><TESTID>200</TESTID><HISTORYID>100<HISTORYID><TESTID>300</TESTID><HISTORYID>250<HISTORYID></REC>
2 TEST B <REC><TESTID>1000</TESTID><HISTORYID>2345<HISTORYID></REC>
3 TEST C <REC><TESTID>100</TESTID><HISTORYID>150<HISTORYID></REC>
答案 0 :(得分:1)
drop table #testmachine
drop table #testdetail
create table #testmachine (oid int , name nvarchar(10))
create table #testdetail (oid int, machineoid int, testid int, historyid int)
insert into #testmachine (oid, name) values (1,'A')
insert into #testmachine (oid, name) values (2,'B')
insert into #testmachine (oid, name) values (3,'C')
insert into #testdetail (oid, machineoid,testid,historyid) values (1,1,10,20)
insert into #testdetail (oid, machineoid,testid,historyid) values (2,1,30,40)
insert into #testdetail (oid, machineoid,testid,historyid) values (3,2,50,60)
insert into #testdetail (oid, machineoid,testid,historyid) values (4,2,70,80)
insert into #testdetail (oid, machineoid,testid,historyid) values (5,3,90,100)
select
tm.oid,
tm.name,
(
select testid, historyid
from #testdetail td
where td.machineoid = tm.oid
for xml path('rec') , root('signal')
) as XMLvalue
from
#testmachine tm
输出
1 A <signal><rec><testid>10</testid><historyid>20</historyid></rec><rec><testid>30</testid><historyid>40</historyid></rec></signal>
2 B <signal><rec><testid>50</testid><historyid>60</historyid></rec><rec><testid>70</testid><historyid>80</historyid></rec></signal>
3 C <signal><rec><testid>90</testid><historyid>100</historyid></rec></signal>
答案 1 :(得分:0)
你需要的是一个“for循环”并用它填充一个额外的表。
循环遍历testmachine表,并为每个OID选择testdetail中的所有记录,然后使用另一个嵌套for循环逐个添加子句
SET TESTXML = CONCAT(TESTXML,new_value)