Get followin sibling in SQL Server XPath - sql-server

Since SQL Server does not support following-sibling axis - what is the best way to get it? Let's say I have XML like this and I would like to get the first 'b' node after a node matching the value 'dog':
<root>
<a>cat</a>
<b>Cats don't like milk</b>
<a>dog</a>
<b>Dogs like everything</b>
</root>

You could try something like this.
declare #X xml = '
<root>
<a>cat</a>
<b>Cats don''t like milk</b>
<a>dog</a>
<c>not this</c>
<b>Dogs like everything</b>
<b>and not this</b>
</root>'
select #X.query('(/root/b[. >> (/root/a[. = "dog"])[1]])[1]')

Related

Is that valid XML and how to replicate with SQL Server

I do have to replicate an XML file with SQL Server and I am now stumbling over the following structure inside the XML file and I don't know how to replicate that.
The structure looks like this at the moment for certain tags:
<ART_TAG1>
<UNMLIMITED/>
</ART_TAG1>
<ART_TAG2>
<ART_TAG3>
<Data_Entry/>
</ART_TAG3>
</ART_TAG2>
I am wondering if this is proper XML that the data inside (unlimited and Data_Entry) is enclosed with a closing XML tag. The XML validator https://www.w3schools.com/xml/xml_validator.asp is telling me this is correct. But now I am struggling with replicating that with Transact-SQL.
If I try to replicate that I can only come up with the following TSQL script, which obviously does not fully look like the original.
SELECT 'UNLIMITED' as 'ART_TAG1'
, 'Data_Entry' as 'ART_TAG2/ART_TAG3'
FOR XML PATH(''), ROOT('root')
<root>
<ART_TAG1>UNLIMITED</ART_TAG1>
<ART_TAG2>
<ART_TAG3>Data_Entry</ART_TAG3>
</ART_TAG2>
</root>
If I get this correctly, your question is:
How can I put my query to create those <SomeElement /> tags?
Look at this:
--This will create filled nodes
SELECT 'outer' AS [OuterNode/#attr]
,'inner' AS [OuterNode/InnerNode]
FOR XML PATH('row');
--The empty string is some kind of content
SELECT 'outer' AS [OuterNode/#attr]
,'' AS [OuterNode/InnerNode]
FOR XML PATH('row');
--the missing value (NULL) is omited by default
SELECT 'outer' AS [OuterNode/#attr]
,NULL AS [OuterNode/InnerNode]
FOR XML PATH('row');
--Now check what happens here:
--First XML has an empty element, while the second uses the self-closing element
DECLARE #xml1 XML=
N'<row>
<OuterNode attr="outer">
<InnerNode></InnerNode>
</OuterNode>
</row>';
DECLARE #xml2 XML=
N'<row>
<OuterNode attr="outer">
<InnerNode/>
</OuterNode>
</row>';
SELECT #xml1,#xml2;
The result is the same for both...
Some background: Semantically the empty element <element></element> is exactly the same as the self-closing element <element />. It should not make any difference, whether you use the one or the other. If your consumer cannot deal with this, it is a problem in the reading part.
Yes, you can force any content into XML on string level, but - as the example shows above - this is just a (dangerous) hack.
XML within T-SQL returns - by default - a missing node as NULL and an empty element as empty (depending on the datatype, and beware of the difference between an element and its text() node).
In short: This is nothing you should have to think about...

Trying to query XML Data - node has a space in it

I am trying to learn how to work with xml files and data in SQL Server and I'm trying to query an xml file but nothing is returned.
Here is the xml data:
<?xml version="1.0" encoding="UTF-8"?>
<Report xmlns="AdmissionsByPCP" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="AdmissionsByPCP" xsi:schemaLocation="AdmissionsByPCP http://10.xxx.x.xx/ReportServer_NameofReportServer?%2FHl%20C%20Syst%20Reports%2health%2FAdmissBy&rs%3ACommand=Render&rs%3AFormat=XML&rs%3ASessionID=h0iz5ijxgt2vdl45g3pjfs45&rc%3ASchema=True">
<Tablix2>
<Details_Collection>
<Details PCPCarrier="DoctorsName">
<Subreport1>
<Report Name="PCPAdmitSubReport">
<Tablix5 Textbox5="79">
<Details_Collection>
<Details Textbox37="Discharge Dx Code: ICDCode" Textbox89="Admit Dx Code: ICDCode" LOS="4" DischargeDate="07/10/2017" AdmitDate="07/06/2017" Hospital="Hospital Name" MemberName="Name" DOB="1/1/2019" AdmissionType="Inpatient" MemberNo="12345" Auth="321*I" Status="Close" AdmissionID="00001" LobName="Medicare" CarrierName="CarrierName"/>
</Details></Details_Collection></Tablix5></Report></Subreport1></Details></Details_Collection></Tablix2></Report>
Here is the query I'm using:
Declare #XMLData as XML
Set #XMLData=(
Select bulkcolumn
FROM OPENROWSET (Bulk '\Directory\AdmissionsByPCP.xml',
Single_Blob) a)
Select
#XMLData.value('(/Root/Report/Tablix2/Detail_Collections/DetailsPCPCarrier) [1]', 'varchar(max)') PCP
The query returns null and I don't know why. Is it because there is a space in the node (<Details PCPCarrier>) and if so how do I work around that?
You have misunderstood how XML works. This is the node you are looking for:
<Details PCPCarrier="DoctorsName">
This is not a node called Details PCPCarrier; it is a node called Details with an attribute called PCPCarrier.
So the XPath to select it would be:
/Root/Report/Tablix2/Detail_Collections/Details
Or, if you want to specifically filter by the PCPCarrier attribute existing:
/Root/Report/Tablix2/Detail_Collections/Details[#PCPCarrier]
Or, to get the value of the attribute itself:
/Root/Report/Tablix2/Detail_Collections/Details/#PCPCarrier
IMSoP pointed me in the right direction and I figured out the rest myself.
I also needed to add this:
With XMLNAMESPACES (Default 'AdmissionsByPCP')
So the query looks like this:
Declare #XMLData as XML
Set #XMLData=(
Select *
FROM OPENROWSET (Bulk '\\Directory\AdmissionsByPCP.xml',
Single_Clob) a );
With XMLNAMESPACES (Default 'AdmissionsByPCP')
Select
#XMLData.value('(/Report/Tablix2/Details_Collection/Details/#PCPCarrier)
[1]', 'varchar(max)')

loading xml File into SQL Server table is not working.

I have XML file that I am trying to load into SQL server but when I run the script, it is not displaying any rows.
<root>
<DeviceRecord xmlns="http://www.archer-tech.com/">
<IP>137.52</IP>
<FQDN>sdcww00</FQDN>
<NetBios_Name></NetBios_Name>
<Operating_System>Microsoft Windows Vista</Operating_System>
<Mac_Address></Mac_Address>
<Confidence_Level>65
</Confidence_Level>
</DeviceRecord>
<DeviceRecord xmlns="http://www.archer-tech.com/">
<IP>155.37.51</IP>
<FQDN>ww00048</FQDN>
<NetBios_Name></NetBios_Name>
<Operating_System>Microsoft Windows Vista</Operating_System>
<Mac_Address></Mac_Address>
<Confidence_Level>65
</Confidence_Level>
</DeviceRecord>
</root>
SQL Script
declare #xmldata as xml
set #xmldata= (SELECT CONVERT(XML, BulkColumn) AS BulkColumn
FROM OPENROWSET(BULK 'C:\Users\ag03536\Documents\New folder\updated.xml', SINGLE_BLOB)as X)
SELECT
x.Rec.query('./DeviceRecord').value('.','varchar(120)')
,x.Rec.query('./IP').value('.','varchar(20)')
,x.Rec.query('./FQDN').value('.','varchar(20)')
FROM #xmldata.nodes('./root') as x(rec)
First you have to check, whether the XML is read propperly. Use this after reading your XML into the variable:
SELECT #xmldata;
Secondly all your values live in a default namespace. You have to declare it:
WITH XMLNAMESPACES(DEFAULT 'http://www.archer-tech.com/')
Third, your query should read all nested <DeviceRecord> entries probably, you need .nodes() down to this level. The full query should be something like this:
WITH XMLNAMESPACES(DEFAULT 'http://www.archer-tech.com/')
SELECT
x.Rec.value('(IP/text())[1]','varchar(20)') AS DevRec_ID
,x.Rec.value('(FQDN/text())[1]','varchar(20)') AS DevRec_FQDN
--The rest should be the same approach...
FROM #xmldata.nodes('/*:root/DeviceRecord') as x(rec)
EDIT: Your node <root> is not part of the default namespace.
I used a wildcard (*:root)

SQL Server Stored Procedure XML can't get node right

I have this query here:
SELECT [Job_No] as '#Key',
(
)
FOR XML PATH('Job_No'), ROOT('Root')
and it returns like so:
<Root>
<Job_No Key="ORC0023">
</Job_No>
</Root>
How do I get it like so:
<Root>
<Key>ORC0023</Key>
</Root>
try this:
SELECT [Job_No] as 'Key' FROM Jobs
FOR XML PATH(''), root ('Root');
working fiddle

Generate XML in proper syntax from SQL Server table

How to write a SQL statement to generate XML like this
<ROOT>
<Production.Product>
<ProductID>1 </ProductID>
<Name>Adjustable Race</Name>
........
</Production.Product>
</ROOT>
Currently I am getting this with
SELECT * FROM Production.Product
FOR XML auto
Result is:
<ROOT>
<Production.Product ProductID="1" Name="Adjustable Race"
ProductNumber="AR-5381" MakeFlag="0" FinishedGoodsFlag="0"
SafetyStockLevel="1000" ReorderPoint="750" StandardCost="0.0000"
ListPrice="0.0000" DaysToManufacture="0" SellStartDate="1998-06-01T00:00:00"
rowguid="694215B7-08F7-4C0D-ACB1-D734BA44C0C8"
ModifiedDate="2004-03-11T10:01:36.827" />
One simple way would be to use:
SELECT *
FROM Production.Product
FOR XML AUTO, ELEMENTS
Then, your data should be stored in XML elements inside the <Production.Product> node.
If you need even more control, then you should look at the FOR XML PATH syntax - check out this MSDN article on What's new in FOR XML in SQL Server 2005 which explains the FOR XML PATH (among other new features).
Basically, with FOR XML PATH, you can control very easily how things are rendered - as elements or as attributes - something like:
SELECT
ProductID AS '#ProductID', -- rendered as attribute on XML node
Name, ProductNumber, -- all rendered as elements inside XML node
.....
FROM Production.Product
FOR XML PATH('NewProductNode') -- define a new name for the XML node
This would give you something like:
<NewProductNode ProductID="1">
<Name>Adjustabel Race</Name>
<ProductNumber>AR-5381</ProductNumber>
.....
</NewProductNode>

Resources