Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

sql - Need to fetch both Columns in XML Nodes?

Is it possible to get the 'A' and 'B' Columns in the Same(Single) SELECT Statement instead of using the 2 SELECT Statements:

Tried query:

DECLARE @Invoice_Types  VARCHAR(MAX)='T-E,T-I,3-E,D-E,D-I'
,@Invoice_TypesXML XML

SET @Invoice_TypesXML=CAST(('<I>'+REPLACE(REPLACE(@Invoice_Types,',','</R><I>'),'-' ,'</I><R>') +'</R>') 
AS XML);

SELECT I.value('.', 'VARCHAR(MAX)') A                        
FROM @Invoice_TypesXML.nodes('I') AS FN(I)

SELECT R.value('.', 'VARCHAR(MAX)') B                       
FROM @Invoice_TypesXML.nodes('R') AS FN(R)

Expected Result: in Single Select Statement

 A   B
-----------------
T   E
T   I
3   E
D   E
D   I  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For your requirement, you need to revise your XML structure like this:

    <Item>
          <I>T</I><R>E</R>
   </Item>
    <Item>
          <I>T</I><R>I</R>
   </Item>
    <Item>
          <I>3</I><R>E</R>
   </Item>
    <Item>
          <I>D</I><R>E</R>
   </Item>
    <Item>
          <I>D</I><R>I</R>
   </Item>

And then you can select your final result in one select statement.

Try this:

DECLARE @Invoice_Types  VARCHAR(MAX)='T-E,T-I,3-E,D-E,D-I'
,@Invoice_TypesXML XML

SET @Invoice_TypesXML=CAST(('<Item><I>'+REPLACE(REPLACE(@Invoice_Types,',','</R></Item><Item><I>'),'-' ,'</I><R>') +'</R></Item>') 
AS XML);


SELECT 
    x.Rec.query('./I').value('.', 'nvarchar(2000)') AS 'A',
    x.Rec.query('./R').value('.', 'nvarchar(2000)') AS 'B'
FROM @Invoice_TypesXML.nodes('/Item') as x(Rec)

Final result:

A   B
_____
T   E
T   I
3   E
D   E
D   I

See this Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...