Oracle - XMLTABLE PATH get node ancestor - sql

I have XML that looks like:
<root>
<uid>789</uid>
<element>
<uid>123</uid>
<sub>
<text>XYZ</text>
</sub>
</element>
</root>
The only constant thing is <text> node and the fact that <uid> node could be 2 level up. Rest of nodes could have any name so I cannot use fully qualified paths.
Based of <text> node I need to find <uid> node which is the nearest or for simplicity 2 levels up in the tree.
I tried:
WITH cte("XML") AS (
SELECT '<root>
<uid>789</uid>
<element>
<uid>123</uid>
<sub>
<text>XYZ</text>
</sub>
</element>
</root>'
FROM dual
)
SELECT x.*, c.*
FROM cte c,XMLTable('//text'
PASSING XMLTYPE(c."XML")
COLUMNS
text VARCHAR2(4000) PATH '.'
--,guid VARCHAR2(40) PATH '../../uid' -- unsupported XQuery expression
--,guid VARCHAR2(40) PATH 'ancestor::node()[2]/uid'
-- unsupported XQuery expression\
) x
WHERE text IS NOT NULL;
db<>fiddle demo
I am looking for solution similar to SQL Server:
WITH cte("XML") AS (
SELECT CAST('<root>
<uid>789</uid>
<element>
<uid>123</uid>
<sub>
<text>XYZ</text>
</sub>
</element>
</root>' AS XML)
)
SELECT x.value('../../uid[1]', 'VARCHAR(10)') AS uid
,s.x.value('.', 'VARCHAR(10)') AS "text"
FROM cte c
CROSS APPLY c."XML".nodes('//text') s(x)
db<>fiddle demo

You should use preceding - it will return all nodes except any ancestor.
Order of preceding collection is from the beginning to the end.
If you do this preceding::uid or more general preceding::* result will be (789, 123).
Combining everything together:
WITH cte("XML") AS (
SELECT '<root>
<uid>789</uid>
<element>
<uid>123</uid>
<sub>
<text>XYZ</text>
</sub>
</element>
</root>'
FROM dual
)
SELECT x.*, c.*
FROM cte c,XMLTable('//text'
PASSING XMLTYPE(c."XML")
COLUMNS
text VARCHAR2(4000) PATH '.'
,guid VARCHAR2(40) PATH '(preceding::uid)[last() -1]/data(.)' -- 2 -levelup
) x
WHERE text IS NOT NULL;

One working solution is the following:
SELECT x.*, c.*
FROM cte c,XMLTable('//text/../..'
PASSING XMLTYPE(c."XML")
COLUMNS
text VARCHAR2(4000) PATH 'uid',
guid VARCHAR2(40) PATH 'sub/text'
) x
WHERE text IS NOT NULL;
Its result consists of the two columns 123 and XYZ.

Related

Sql2012 FOR XML Inconsistent "empty element" Behavior

I have an empty string in a table that I am selecting into XML. Ideally, this will produce an empty element, like <name /> instead of <name></name>.
It seems that if my empty string is the only thing I select, I get the undesired (verbose) empty tag ... but if I select other things, including another empty string (or the same empty string), I get the desirable empty tag ().
Can anyone tell me why this happens? And more importantly, how to control it?
declare #table table( TextValue nvarchar(100) )
insert into #table( TextValue ) values ( '' )
select
( select t.TextValue name for xml path( '' ), type )
from #table t
for xml path( 'row' ), root( 'root' ), type
/* result:
<root>
<row>
<name></name> <!-- select just once, verbose -->
</row>
</root>
*/
select
( select t.TextValue name for xml path( '' ), type ),
( select t.TextValue name for xml path( '' ), type )
from #table t
for xml path( 'row' ), root( 'root' ), type
/* result:
<root>
<row>
<name /> <!-- select twice, nice and neat -->
<name />
</row>
</root>
*/
Thanks!
It made me curious too:
That's what I came up with:
If you tell the XML engine to create XML it is done the way
open the element
fill in the content
close the element
All of these example lead to <element></element>
select '' name
for xml path( 'row' )
select '' name
,'' name2
for xml path( 'row' )
select '' name
,''
,'' name
for xml path( 'row' )
But if the XML-elment was created before the XML Engine is dealing with it, the (better) short form is used.
All of them lead to <element/>
select CAST('<name></name>' AS XML)
for xml path( 'row' )
select CAST('<name/>' AS XML)
for xml path( 'row' )
select (SELECT '' AS name FOR XML PATH(''),TYPE)
for xml path( 'row' )
UPDATE
You even can combine this
select (SELECT '' AS name FOR XML PATH(''),TYPE)
,'' AS name
for xml path( 'row' )
leads to
<row>
<name />
<name></name>
</row>
UPDATE 2
I think this has nothing to do with the element name's length. Neither is it bound to the count of columns you call. This is merely bound to: Is the XML created this moment or was it create before?
DECLARE #n1 VARCHAR(100)='';
DECLARE #n2 XML='<name></name>';
DECLARE #n3 XML='<name/>';
SELECT #n1 AS name FOR XML PATH('root');
SELECT #n2 FOR XML PATH('root');
SELECT #n3 FOR XML PATH('root');

Generate XML of the Structure of a table when it's empty in SQL Server

I am trying to generate a table containing one row that contains the XML of each temporary table in a stored procedure.
The problem is when the table is empty the FOR XML PATH('RS'), root('OR_RS') returns null.
What I want is: when the table is empty, return the structure of this table
something like this :
<OR_RS>
<ContactCode></ContactCode>
<EmailPaper></EmailPaper>
<ShortEmail></ShortEmail>
<WebSite></WebSite>
<Providers></Providers>
</OR_RS>
I have tried to do this :
-- ,ISNULL( (SELECT * FROM #OR_RS FOR XML PATH('RS'), root('OR_RS')), (SELECT ISNULL(ContactCode,'') , ISNULL(EmailPaper,'') , ISNULL(ShortEmail,'') , ISNULL(WebSite,'') , ISNULL(Providers,'') FROM #OR_RS FOR XML RAW)) as OR_RS
but it returns always Null:
SELECT 1 as Id, (SELECT * FROM #OR_MK FOR XML PATH('MK'), root('OR_MK') ) as OR_MK
,(SELECT * FROM #OR_CA FOR XML PATH('CA'), root('OR_CA') ) as OR_CA
-- ,ISNULL( (SELECT * FROM #OR_RS FOR XML PATH('RS'), root('OR_RS')), (SELECT ISNULL(ContactCode,'') , ISNULL(EmailPaper,'') , ISNULL(ShortEmail,'') , ISNULL(WebSite,'') , ISNULL(Providers,'') FROM #OR_RS FOR XML AUTO)) as OR_RS
,(SELECT * FROM #OR_RS FOR XML PATH('RS'), root('OR_RS')) as OR_RS
,(SELECT * FROM #OR_DC FOR XML PATH('DC'), root('OR_DC') ) as OR_DC
,(SELECT * FROM #BENEFICIARY FOR XML PATH('BEN'), root('BENEFICIARY') ) as BENEFICIARY
,(SELECT * FROM #MK_REPORT for XML PATH('REP'), root('MK_REPORT')) as MK_REPORT
Whatever you try to do with this...
You might want to have a look at sp_describe_first_result_set, but, since this is a procedure, it will not be that easy to get its result into your query...
You can use a trick (a RIGHT JOIN) to enforce a resultset. And with ELEMENTS XSINIL you force the engine to include the column in any case. Otherwise XML takes missing elements as NULL, so your empty result would not be written into the result XML at all otherwise. Try this:
DECLARE #tbl TABLE(ID INT IDENTITY,SomeValue INT,SomeString VARCHAR(100));
SELECT *
FROM #tbl
RIGHT JOIN (SELECT 1 AS x) AS tbl ON 1=1
FOR XML RAW, ELEMENTS XSINIL
The result
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID xsi:nil="true" />
<SomeValue xsi:nil="true" />
<SomeString xsi:nil="true" />
<x>1</x>
</row>
If you want to get more details, you might add ,XMLDATA or ,XMLSCHEMA to generate full meta data.

Incorrect structure of XML generated in SQL

Iv had another problem, i just change my UNION to UNION ALL and it work correctly but i want to add another XML path (at the beginning) - this will be a const for both querys.
(SELECT 1 AS "ns0:kindOfItem",
code AS "ns0:wholeCode",
REPLACE(weight, ',', '.') AS "ns0:weight",
1 AS "ns0:ammountOfNumbers",
(SELECT price AS "ns0:value",
'EUR' as "ns0:currency"
FOR XML PATH ('ns0:sendedItems'), TYPE),
(SELECT
'EUR' as "ns0:currency"
FOR XML PATH ('ns0:present'), TYPE)
FROM [PL].[dbo].[dk_documents] where id in (1,2,3)
UNION ALL
(SELECT 1 AS "ns0:kindOfItem",
code AS "ns0:wholeCode",
REPLACE(weight, ',', '.') AS "ns0:weight",
1 AS "ns0:ammountOfNumbers",
(SELECT price AS "ns0:value",
'EUR' as "ns0:currency"
FOR XML PATH ('ns0:sendedItems'), TYPE),
(SELECT
'EUR' as "ns0:currency"
FOR XML PATH ('ns0:present'), TYPE)
FROM [PL2].[dbo].[dk_documents] where id in (1,2,3)
FOR XML PATH('test'))
It work correctly but i want sth like this :
SELECT 1 as test,
(SELECT 1 AS "ns0:kindOfItem",
code AS "ns0:wholeCode",
REPLACE(weight, ',', '.') AS "ns0:weight",
1 AS "ns0:ammountOfNumbers",
(SELECT price AS "ns0:value",
'EUR' as "ns0:currency"
FOR XML PATH ('ns0:sendedItems'), TYPE),
(SELECT
'EUR' as "ns0:currency"
FOR XML PATH ('ns0:present'), TYPE)
FROM [PL].[dbo].[dk_documents] where id in (1,2,3)
UNION ALL
(SELECT 1 AS "ns0:kindOfItem",
code AS "ns0:wholeCode",
REPLACE(weight, ',', '.') AS "ns0:weight",
1 AS "ns0:ammountOfNumbers",
(SELECT price AS "ns0:value",
'EUR' as "ns0:currency"
FOR XML PATH ('ns0:sendedItems'), TYPE),
(SELECT
'EUR' as "ns0:currency"
FOR XML PATH ('ns0:present'), TYPE)
FROM [PL2].[dbo].[dk_documents] where id in (1,2,3)
FOR XML PATH('test'))
FOR XML PATH('anotherPath')
i got this error:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Output should be like
<test>1</test>
<>All of tese columns from QUERY with union ALL</>
Just an example :
WITH XMLNAMESPACES(DEFAULT 'Dummy')
SELECT 1 as test,
2 as anotherOne,
(SELECT * FROM
(SELECT id, symbol from table1
WHERE id in (1,2,3)
UNION ALL
SELECT id, nrdok from table2
WHERE id in (4,5,6))as yolo
FOR XML PATH(''),TYPE)
FOR XML PATH('test')
It gives me an output :
<test xmlns="Dummy">
<test>1</test>
<anotherOne>2</anotherOne>
<id xmlns="Dummy">1</id>
<symbol xmlns="Dummy">test10</symbol>
<id xmlns="Dummy">2</id>
<symbol xmlns="Dummy">test10</symbol>
<id xmlns="Dummy">3</id>
<symbol xmlns="Dummy">test10</symbol>
<id xmlns="Dummy">4</id>
<symbol xmlns="Dummy">test11</symbol>
<id xmlns="Dummy">5</id>
<symbol xmlns="Dummy">test11</symbol>
<id xmlns="Dummy">6</id>
<symbol xmlns="Dummy">test11</symbol>
</test>
And i want :
<test xmlns="Dummy">
<test>1</test>
<anotherOne>2</anotherOne>
<id>1</id>
<symbol>test10</symbol>
<id>2</id>
<symbol>test10</symbol>
<id>3</id>
<symbol>test10</symbol>
<id>4</id>
<symbol>test11</symbol>
<id>5</id>
<symbol>test11</symbol>
<id>6</id>
<symbol>test11</symbol>
</test>
As pointed out at your previous question the repeated namespaces are not wrong, just annoying, and - if there are many and long URIs, they can blow up your XML to remarkable size...
There I placed a link to a related question already. The trick is to create the XML without the namespace and add the namespace in the finaly SELECT ... FOR XML PATH only:
But I must admit, that after a long while of trial and error I found, that there seem to be a bug if the DEFAULT namespace is involved. Any approach I tried led to either repeated namespace declarations or to repeated empty namespace declarations.
So the only solution I could find is this (I go to wash my fingers now :-) ):
DECLARE #table1 TABLE(id INT,symbol VARCHAR(100));
INSERT INTO #table1 VALUES
(1,'Test 1')
,(2,'Test 2')
,(3,'Test 3')
,(4,'Test 4');
DECLARE #nordic_table2 TABLE(id INT,nrdok VARCHAR(100));
INSERT INTO #nordic_table2 VALUES
(1,'Test 1')
,(2,'Test 2')
,(3,'Test 3')
,(4,'Test 4');
DECLARE #XmlWithoutNamespace XML=
(
SELECT 1 as test
,2 as anotherOne
,(
SELECT *
FROM
(
SELECT id, symbol from #table1
WHERE id in (1,2,3)
UNION ALL
SELECT id, nrdok from #nordic_table2
WHERE id in (4,5,6)
) AS yolo
FOR XML PATH(''),TYPE
)
FOR XML PATH('')
);
SELECT
CAST(
'<test xmlns="Dummy">'
+
CAST(#XmlWithoutNamespace AS NVARCHAR(MAX))
+
'</test>'
AS XML);
UPDATE
I strongly advise you to change your structure to this
SELECT id AS [#id]
,symbol AS [*]
FROM
(
SELECT id, symbol from #table1
WHERE id in (1,2,3)
UNION ALL
SELECT id, nrdok from #nordic_table2
WHERE id in (4,5,6)
) AS yolo
FOR XML PATH('symbol'),TYPE
The result would be this, which is much better to read and to query...
<test xmlns="Dummy">
<test>1</test>
<anotherOne>2</anotherOne>
<symbol id="1">Test 1</symbol>
<symbol id="2">Test 2</symbol>
<symbol id="3">Test 3</symbol>
<symbol id="4">Test 4</symbol>
</test>
UPDATE 2: More Namespaces...
It is actually really hard - almost impossible - to deal with namespaces properly. There is some highly developed logic within FOR XML PATH and in methods like .modify(). I tried several approaches but did not find a convincing one...
The only way I found is very ugly. The trick is, to create 1-level-XML only (no nested elements from sub-selects!) and store them as strings. But before you cut away the root with the namespace declarations. Doing so you'll get invalid XML fragments.
You concatenate them and CAST the whole lot in the last step back to XML.
--Just a container to collect the XML parts
DECLARE #CollectXML TABLE(ID INT IDENTITY,Content XML,CleanedAsString NVARCHAR(MAX));
--The final ",ROOT('xyz')" will force the namespace's declaration into the root node
WITH XMLNAMESPACES('SomeTestUri' AS abc)
INSERT INTO #CollectXML(Content)
SELECT
(
SELECT 1 as [abc:test]
,2 as anotherOne
FOR XML PATH(''),ROOT('xyz'),TYPE
);
--No we use ugly string manipulation to cut out the inner part without the namespace declaration
UPDATE #CollectXML SET CleanedAsString=
(
SELECT Rest
FROM #CollectXML
CROSS APPLY (SELECT CAST(Content AS NVARCHAR(MAX))) AS Casted(XmlAsString)
CROSS APPLY (SELECT REVERSE(SUBSTRING(XmlAsString,CHARINDEX('>',XmlAsString)+1,LEN(XmlAsString)))) AS Cut1(part1Reverse)
CROSS APPLY (SELECT REVERSE(SUBSTRING(part1Reverse,CHARINDEX('<',part1Reverse)+1,LEN(part1Reverse)))) AS Cut2(Rest)
WHERE ID=1
)
WHERE ID=1;
--The same with the second part
WITH XMLNAMESPACES('SomeTestUri' AS abc)
INSERT INTO #CollectXML(Content)
SELECT
(
SELECT id AS [#abc:id]
,symbol AS [*]
FROM
(
SELECT id, symbol from #table1
WHERE id in (1,2,3)
UNION ALL
SELECT id, nrdok from #nordic_table2
WHERE id in (4,5,6)
) AS yolo
FOR XML PATH('abc:symbol'),ROOT('xyz'),TYPE --the not needed root will take the namespace declaration out of the deeper elements
);
--and the ugly string manipulation
UPDATE #CollectXML SET CleanedAsString=
(
SELECT Rest
FROM #CollectXML
CROSS APPLY (SELECT CAST(Content AS NVARCHAR(MAX))) AS Casted(XmlAsString)
CROSS APPLY (SELECT REVERSE(SUBSTRING(XmlAsString,CHARINDEX('>',XmlAsString)+1,LEN(XmlAsString)))) AS Cut1(part1Reverse)
CROSS APPLY (SELECT REVERSE(SUBSTRING(part1Reverse,CHARINDEX('<',part1Reverse)+1,LEN(part1Reverse)))) AS Cut2(Rest)
WHERE ID=2
)
WHERE ID=2;
--The XML is put together and - as the very last step! - casted back to XML
SELECT
CAST(
'<test xmlns="Dummy" xmlns:abc="SomeTestUri">'
+
(SELECT CleanedAsString FROM #CollectXML WHERE ID=1)
+
(SELECT CleanedAsString FROM #CollectXML WHERE ID=2)
+
'</test>'
AS XML);
The result for this
<test xmlns="Dummy" xmlns:abc="SomeTestUri">
<abc:test>1</abc:test>
<anotherOne>2</anotherOne>
<abc:symbol abc:id="1">Test 1</abc:symbol>
<abc:symbol abc:id="2">Test 2</abc:symbol>
<abc:symbol abc:id="3">Test 3</abc:symbol>
<abc:symbol abc:id="4">Test 4</abc:symbol>
</test>
You can test below SQL Select statement.
I hope it helps,
declare #xml xml
declare #xml1 xml
set #xml1 = '<test>1</test>'
declare #xml2 xml
set #xml2 = ( select top 4 name from sys.databases FOR XML PATH('database') )
set #xml = (SELECT #xml1, #xml2 FOR XML PATH(''))
select #xml
Output will be as follows

how to generate xml with element and attribute using xml explicit

im trying to generate xml in the following format:
<Root>
<Domain>Abc</Domain>
<Name>Xyz</Name>
<Contents>
<Content>
<ID>1</ID>
<Value>Test 1</Value>
<Record ID="1">Test 1</Record>
</Content>
<Content>
<ID>2</ID>
<Value>Test 2</Value>
<Record ID="2">Test 2</Record>
</Content>
</Contents>
</Root>
My query is as follows:
declare #TestTable table (ID int, Value varchar(100))
insert into #TestTable values (1,'Test 1')
insert into #TestTable values (2,'Test 2')
declare #Domain varchar(max)='Abc'
declare #Name varchar(max)='Xyz'
SELECT
1 AS Tag,
NULL AS Parent,
#Domain as 'Root!1!Domain!Element',
#Name as 'Root!1!Name!Element',
NULL as 'Contents!2!Element',
NULL as 'Content!3!ID!Element',
NULL as 'Content!3!Value!Element',
NULL as 'Content!3!Record!Element'
union
SELECT
2 AS Tag,
1 AS Parent,
NULL,NULL,NULL,NULL,NULL,NULL
union
select
3 as Tag,
2 as Parent,
NUll,NUll,NULL,
ID,Value,Value
from #TestTable
FOR XML EXPLICIT
my query does not produce the record tag completely, currently it is
<Record>Test 2</Record>
which should be as
<Record ID=2>Test 2</Record>
I tried all the possibilities but not getting the tag. Can anyone help me solving this issue.
I could not get the expected output from xml explicit, instead i used xml path and got the output. this is my updated query
SELECT
#Domain "Domain",
#Name "Name",
(
SELECT
ID "ID",
Value "Value",
(select
ID "#ID",
Value as "text()"
FOR XML PATH('Record'), ELEMENTS, TYPE )
FROM #TestTable
FOR XML PATH ('Content'), TYPE, ROOT('Contents')
)
FOR XML PATH ('Root')
you are welcome to post the fix which uses xml explicit.
Don't forget the ORDER BY when use FOR XML EXPLICIT.
SELECT
1 AS Tag,
NULL AS Parent,
#Domain as 'Root!1!Domain!Element',
#Name as 'Root!1!Name!Element',
NULL as 'Contents!2!Element',
NULL as 'Content!3!ID!Element',
NULL as 'Content!3!Value!Element',
NULL as 'Record!4!ID',
NULL as 'Record!4!'
union
SELECT
2 AS Tag,
1 AS Parent,
#Domain,NULL,NULL,NULL,NULL,NULL, null
union
select
3 as Tag,
2 as Parent,
#Domain,NUll,NULL,
ID,Value,null,null
from #TestTable
union
select
4 as Tag,
3 as Parent,
#Domain,NUll,NULL,
ID,Value,ID,Value
from #TestTable
ORDER BY 'Root!1!Domain!Element','Contents!2!Element','Content!3!ID!Element','Record!4!ID'
FOR XML EXPLICIT

How to Generate xml from sql for below pattern

I'm writing one stored procedure, which I have to create a xml column from db.
µ = CHAR(181) this is value separator,
¶ = CHAR(182) this is row separator
This is the statement I wrote. I know its not well formed.
SELECT #xmlString= CAST('<root><Section> ID =' + REPLACE(REPLACE ('20211µ1¶20212µ2', CHAR(182),
'</Section><Section> ID ='),CHAR(181), ' Slno=') + '</Section></root>' AS XML)
This is the pattern which I need to display like this.
<root>
<sections id="20211" slno="1" ></sections>
<sections id="20215" slno="2" ></sections>
</root>
declare #s varchar(50) = '20211µ1¶20212µ2'
declare #xmlString xml
;with C as
(
select T.N.value('value[1]', 'int') as id,
T.N.value('value[2]', 'int') as slno
from (select cast('<item><value>'+replace(replace(#s, 'µ','</value><value>'), '¶','</value></item><item><value>')+'</value></item>' as xml)) as X(XMLCol)
cross apply X.XMLCol.nodes('item') as T(N)
)
select #xmlString =
(
select C.id as [#id] ,
C.slno as [#slno]
from C
for xml path('sections'), root('root'), type
)
select #xmlString
Result:
<root>
<sections id="20211" slno="1" />
<sections id="20212" slno="2" />
</root>