My question is related to this question. However I am writing a clean scenario on which I need help. I am a beginner in SQL and pardon me If I'm incorrect anywhere.
I have a procedure(huge on. replicating a small sample here) that spits out bunch of XMLs. On my second procedure, based on Parametric condition I have to insert a node in the XML for every CID and do a final select. I am adding a Rextester link below:
UPDATED LINK: http://rextester.com/EFGQB11125
Current output:
<Main>
<ID>1001</ID>
<details>
<name>John</name>
<age>12</age>
</details>
</Main>
<Main>
<ID>1002</ID>
<details>
<name>Rick</name>
<age>19</age>
</details>
</Main>
<Main>
<ID>1003</ID>
<details>
<name>Diane</name>
<age>25</age>
</details>
</Main>
<Main>
<ID>1004</ID>
<details>
<name>Kippy</name>
<age>26</age>
</details>
</Main>
Desired output:
When @type = 'N'/'U' then
<Main>
<ID>1001</ID>
<type>N</type>
<details>
<name>John</name>
<age>12</age>
</details>
</Main>
<Main>
<ID>1002</ID>
<type>U</type>
<details>
<name>Rick</name>
<age>19</age>
</details>
</Main>
<Main>
<ID>1003</ID>
<type>N</type>
<details>
<name>Diane</name>
<age>25</age>
</details>
</Main>
<Main>
<ID>1004</ID>
<type>N</type>
<details>
<name>Kippy</name>
<age>26</age>
</details>
</Main>
So, for every CID, based on @type values, a node should be inserted with that value. Any help?!
(Sorry for being redundant by any chance)
The trick used in the example below uses a bit of Dynamic Sql magic.
Basically building 1 big SQL with all the updates for each ID.
declare @Sql varchar(max);
select @Sql = concat(@Sql,'UPDATE #final SET xml_data.modify(''insert <type>',ctype,'</type> after (/Main/ID)[text()="',cid,'"][1]'');',CHAR(13),CHAR(10))
from #tbl;
-- select @Sql as xml_modify_sqls;
exec(@Sql);
select * from #final;
And here's some SQL to setup the temporary tables with the sample data:
IF OBJECT_ID('tempdb..#tbl') IS NOT NULL DROP TABLE #tbl;
create table #tbl (cid int, ctype varchar(5));
IF OBJECT_ID('tempdb..#cdetails') IS NOT NULL DROP TABLE #cdetails;
create table #cdetails (cid int, name varchar(5), age int);
IF OBJECT_ID('tempdb..#final') IS NOT NULL DROP TABLE #final;
create table #final (xml_data xml);
insert into #tbl (cid, ctype) values
(1001,'N'), (1002,'U'), (1003,'N'), (1004,'N');
insert into #cdetails (cid, name, age) values
(1001,'John',12), (1002,'Rick',19), (1003,'Diane',25), (1004,'Kippy',26);
insert into #final (xml_data)
select xml_data
from (
select
cd1.cid as ID,
-- type = t.ctype as type,
details =
(
select
cd.name,
cd.age
from #cdetails cd
where cd.cid = cd1.cid
For XML Path(''), Type
)
from #cdetails cd1
join #tbl t on cd1.cid = t.cid
For XML Path('Main')
) q(xml_data);
select * from #final;
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加