select same child node from openxml sql stored procedure - sql

I have one XML String as below :
<XML>
<ProductDetail>
<Barcode>170604658</Barcode>
<PropertyDetail>
<PropertyKey>Size</PropertyKey>
<PropertyValue>XXL</PropertyValue>
<PropertyKey>ProdTaxType</PropertyKey>
<PropertyValue>5%</PropertyValue>
</PropertyDetail>
</ProductDetail>
</XML>
i m reading the XML Data via below small query in sp:
SELECT *
FROM OPENXML(#hDoc, 'XML/ProductDetail/PropertyDetail', 2) WITH
(
PropertyKey VARCHAR(200) ,
PropertyValue VARCHAR(200)
)XML
BUT , FOR above i m getting one row data as below :
PropertyKey PropertyValue
Size XXL
BUT , as per XML Defined i want to get the data as per below :
PropertyKey PropertyValue
Size XXL
ProdTaxType 5%
FOR the same chile node name i am getting only one record from xml string. So, please suggest in above sp.

Because your XML is not formed well, it should be like this:
DECLARE #hdoc varchar(max) = '<XML>
<ProductDetail>
<Barcode>150604658</Barcode>
<PropertyDetail>
<PropertyKey>Size</PropertyKey>
<PropertyValue>XXL</PropertyValue>
</PropertyDetail>
<PropertyDetail>
<PropertyKey>ProdTaxType</PropertyKey>
<PropertyValue>5%</PropertyValue>
</PropertyDetail>
</ProductDetail>
</XML>'
In your example the PropertyDetail has duplicate attributes.
It could be also re-written like this:
DECLARE #hdoc varchar(max) = '<XML>
<ProductDetail Barcode="150604658">
<PropertyDetail PropertyKey="Size" PropertyValue="XXL" />
<PropertyDetail PropertyKey="ProdTaxType" PropertyValue="5%" />
</ProductDetail>
</XML>'
Now you would not think of writing:
<PropertyDetail PropertyKey="Size" PropertyValue="XXL"
PropertyKey="ProdTaxType" PropertyValue="5%" />
but the meaning is the same as the XML you have - and duplicate attributes are not allowed.

Related

Creating xml for SQL Server stored procedure

I have a function to insert an item into the database. It takes a lot of values as input and the values are passed as XML.
Consider a sample item XML:
<ROOT>
<Item
ItemName="CarlsApplication"
ItemTypeID="2">
<TSDefaultDescription DefaultitemDescription="C:\t.text"/>
<ItemSellers>
<ComputerObject Alias="" DisplayName="" ServiceName="" UserAccount="" />
<ComputerObject Alias="" DisplayName="" ServiceName="" UserAccount="" />
</ItemSellers>
<ItemOwners>
<ItemOwner Alias="rafchen" FirstName="Rafael" LastName="Chenkov"/>
</ItemOwners>
</Item>
</ROOT>
This has to be passed to stored procedure.
Now, each of these individual values in this XML, I have to extract from somewhere else. I can get the individual values like Item name etc, but how do I organize them into an XML that can be passed?
How do I construct this XML from the values I have?
I guess I will have to make some sort of template with this format and then put variables in that template and fill the variables to prepare the template.
Any help is greatly appreciated.
If I understand what you really want, You can use a query like this to generate that XML:
select
ItemName 'Item/#ItemName', --> Node:`Item` Attribute: `ItemName`
ItemTypeId 'Item/#ItemTypeId',
cast((
select
Alias 'ComputerObject/#Alias',
DisplayName 'ComputerObject/#DisplayName',
ServiceName 'ComputerObject/#ServiceName',
UserAccount 'ComputerObject/#UserAccount'
from
ItemSellers
where
ItemSellers.ItemId = Item.ItemId
for xml path('')) as xml) 'Item/ItemSellers', --> Node:`Item` Sub-Node:`ItemSellers`
cast((
select
Alias 'ItemOwner/#Alias',
FirstName 'ItemOwner/#FirstName',
LastName 'ItemOwner/#LastName'
from
ItemOwners
where
ItemOwners.ItemId = Item.ItemId
for xml path('')) as xml) 'Item/ItemOwners'
from
Item
for xml path('ROOT');
SQL Fiddle Demo

Passing irregular xml file to the stored procedure

I have a sample xml as follows. I am trying to get all or specific data and then insert into the my sql table which has the same columns representing the values coming from xml. I looked through some solutions but the xml files are not formatted like I have in here. Can you help me?
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<VehicleStatusResponse xmlns:ns2=
"http://fms-standard.com/rfms/v1.0.0/xsd/common/position" xmlns="http://fms-standard.com/rfms/v1.0.0/xsd/status">
<VehicleStatus>
<VIN>VF254ANA735752628</VIN>
<TriggerType>TIMER</TriggerType>
<CreatedDateTime>2014-09-08T09:30:20</CreatedDateTime>
<ReceivedDateTime>2014-09-08T09:30:57</ReceivedDateTime>
<GNSSPosition>
<ns2:Latitude>49.18557</ns2:Latitude>
<ns2:Longitude>11.18557</ns2:Longitude>
<ns2:Heading>33</ns2:Heading>
<ns2:Altitude>500</ns2:Altitude>
<ns2:Speed>16.4</ns2:Speed>
<ns2:PositionDateTime>2014-09-08T09:30:20</ns2:PositionDateTime>
</GNSSPosition>
<WheelBasedSpeed>16.07</WheelBasedSpeed>
<TachographSpeed>15.83</TachographSpeed>
<HRTotalVehicleDistance>817.5</HRTotalVehicleDistance>
<EngineTotalFuelUsed>575</EngineTotalFuelUsed>
<FuelLevel1>83</FuelLevel1>
<CatalystFuelLevel>88.48</CatalystFuelLevel>
<GrossCombinationVehicleWeight>10000</GrossCombinationVehicleWeight>
</VehicleStatus>
</VehicleStatusResponse>
You can use an XML type and XML methods if you remove or modify the declaration. The SQL Server XML type only supports UCS-2 encoding and doesn't recognize "standalone". The example below uses string manipulation to tweak the declaration. You'll need to change the data types according to your actual column types and should specify an explicit column list on the INSERT statement. I omitted that in this example only because I didn't want to assume your actual table columns matched the element names in the XML.
DECLARE #xml xml;
DECLARE #xmlString nvarchar(MAX) = N'<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<VehicleStatusResponse xmlns:ns2=
"http://fms-standard.com/rfms/v1.0.0/xsd/common/position" xmlns="http://fms-standard.com/rfms/v1.0.0/xsd/status">
<VehicleStatus>
<VIN>VF254ANA735752628</VIN>
<TriggerType>TIMER</TriggerType>
<CreatedDateTime>2014-09-08T09:30:20</CreatedDateTime>
<ReceivedDateTime>2014-09-08T09:30:57</ReceivedDateTime>
<GNSSPosition>
<ns2:Latitude>49.18557</ns2:Latitude>
<ns2:Longitude>11.18557</ns2:Longitude>
<ns2:Heading>33</ns2:Heading>
<ns2:Altitude>500</ns2:Altitude>
<ns2:Speed>16.4</ns2:Speed>
<ns2:PositionDateTime>2014-09-08T09:30:20</ns2:PositionDateTime>
</GNSSPosition>
<WheelBasedSpeed>16.07</WheelBasedSpeed>
<TachographSpeed>15.83</TachographSpeed>
<HRTotalVehicleDistance>817.5</HRTotalVehicleDistance>
<EngineTotalFuelUsed>575</EngineTotalFuelUsed>
<FuelLevel1>83</FuelLevel1>
<CatalystFuelLevel>88.48</CatalystFuelLevel>
<GrossCombinationVehicleWeight>10000</GrossCombinationVehicleWeight>
</VehicleStatus>
</VehicleStatusResponse>';
SET #xmlString = REPLACE(#xmlString, 'encoding="UTF-8"', 'encoding="UCS-2"');
SET #xmlString = REPLACE(#xmlString, 'standalone="true"', '');
SET #xml = #xmlString;
WITH XMLNAMESPACES (
DEFAULT 'http://fms-standard.com/rfms/v1.0.0/xsd/status'
,'http://fms-standard.com/rfms/v1.0.0/xsd/common/position' AS ns2
)
INSERT INTO dbo.YourTable
SELECT
#xml.value('(/VehicleStatusResponse/VehicleStatus/VIN)[1]', 'varchar(50)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/TriggerType)[1]', 'varchar(50)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/CreatedDateTime)[1]', 'datetime2(3)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/ReceivedDateTime)[1]', 'datetime2(3)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/GNSSPosition/ns2:Latitude)[1]', 'decimal(8,5)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/GNSSPosition/ns2:Longitude)[1]', 'decimal(8,5)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/GNSSPosition/ns2:Heading)[1]', 'int')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/GNSSPosition/ns2:Altitude)[1]', 'int')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/GNSSPosition/ns2:Speed)[1]', 'decimal(8,3)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/GNSSPosition/ns2:PositionDateTime)[1]', 'datetime2(3)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/WheelBasedSpeed)[1]', 'decimal(8,3)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/TachographSpeed)[1]', 'decimal(8,3)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/HRTotalVehicleDistance)[1]', 'decimal(8,3)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/EngineTotalFuelUsed)[1]', 'int')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/CatalystFuelLevel)[1]', 'decimal(8,3)')
, #xml.value('(/VehicleStatusResponse/VehicleStatus/GrossCombinationVehicleWeight)[1]', 'int');
First of all you need to get your value into a declare variable of type XML or into an XML-typed data table column. As your XML contains namespaces you have to declare them in a WITH XMLNAMESPACES first. You might use wildcard syntax (*:), but its better to be as specific as possible.
The .nodes() call navigates to the Level of <VehicleStatus>. All elements below are simply 1:1 and easy to read...
You can try it like this:
DECLARE #xml XML=
N'<VehicleStatusResponse xmlns:ns2=
"http://fms-standard.com/rfms/v1.0.0/xsd/common/position" xmlns="http://fms-standard.com/rfms/v1.0.0/xsd/status">
<VehicleStatus>
<VIN>VF254ANA735752628</VIN>
<TriggerType>TIMER</TriggerType>
<CreatedDateTime>2014-09-08T09:30:20</CreatedDateTime>
<ReceivedDateTime>2014-09-08T09:30:57</ReceivedDateTime>
<GNSSPosition>
<ns2:Latitude>49.18557</ns2:Latitude>
<ns2:Longitude>11.18557</ns2:Longitude>
<ns2:Heading>33</ns2:Heading>
<ns2:Altitude>500</ns2:Altitude>
<ns2:Speed>16.4</ns2:Speed>
<ns2:PositionDateTime>2014-09-08T09:30:20</ns2:PositionDateTime>
</GNSSPosition>
<WheelBasedSpeed>16.07</WheelBasedSpeed>
<TachographSpeed>15.83</TachographSpeed>
<HRTotalVehicleDistance>817.5</HRTotalVehicleDistance>
<EngineTotalFuelUsed>575</EngineTotalFuelUsed>
<FuelLevel1>83</FuelLevel1>
<CatalystFuelLevel>88.48</CatalystFuelLevel>
<GrossCombinationVehicleWeight>10000</GrossCombinationVehicleWeight>
</VehicleStatus>
</VehicleStatusResponse>';
--This is the query
WITH XMLNAMESPACES(DEFAULT 'http://fms-standard.com/rfms/v1.0.0/xsd/status'
,'http://fms-standard.com/rfms/v1.0.0/xsd/common/position' AS ns2)
SELECT vs.value('VIN[1]','nvarchar(max)') AS VehicleStatus_VIN
,vs.value('TriggerType[1]','nvarchar(max)') AS VehicleStatus_TriggerType
,vs.value('CreatedDateTime[1]','datetime') AS VehicleStatus_CreatedDateTime
,vs.value('ReceivedDateTime[1]','datetime') AS VehicleStatus_ReceivedDateTime
,vs.value('(GNSSPosition/ns2:Latitude)[1]','decimal(14,6)') AS VehicleStatus_GNSSPosition_Latitude
,vs.value('(GNSSPosition/ns2:Longitude)[1]','decimal(14,6)') AS VehicleStatus_GNSSPosition_Longitude
/*other columns follow the same pattern*/
FROM #xml.nodes('/VehicleStatusResponse/VehicleStatus') AS A(vs)
update: insert into a table
Easiest was to wrap this call as CTE like
WITH XMLNAMESPACES(...)
,DerivedTableCTE AS
(
The query here
)
INSERT INTO YourTable (col1, col2, col3, ...)
SELECT col1, col2, col3, ...
FROM DerivedTableCTE

Exporting a xml document from sql 2008

All
I have very little experience of xml, so please be gentle.
The situation is we use an application called dataswitch to take xml and process it into our ERP system via business objects.
The output I am trying to recreate is as follows from a sample xml document.
**<?xml version="1.0" encoding="Windows-1252" ?>
- <IssueDetails Language="05" CssStyle="" DecFormat="1" DateFormat="01" Role="01" Version="6.0.000">**
- <Item>
<Job>00000121</Job>
<NonStocked>N</NonStocked>
<Warehouse>RM</Warehouse>
<StockCode>BBMB100</StockCode>
<Line>00</Line>
<QuantityToIssue>1.000</QuantityToIssue>
</Item>
</IssueDetails>
So far I have worked on the For xml Path method to build my query and used the sp from Phil Factor to write the output
So far I have been successful creating an xml document which opens in the browser (many tries required!)
This is the output I have managed to create, please note the top lines are different
**<IssueDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">**
- <Item>
<Job>00044816</Job>
<NonStocked>N</NonStocked>
<Warehouse>C2</Warehouse>
<StockCode>FG00707</StockCode>
<Line>00</Line>
<QuantityToIssue>400.000000000</QuantityToIssue>
</Item>
- <Item>
<Job>00044816</Job>
<NonStocked>N</NonStocked>
<Warehouse>C2</Warehouse>
<StockCode>FG00707</StockCode>
<Line>00</Line>
<QuantityToIssue>10.000000000</QuantityToIssue>
</Item>
</IssueDetails>
So my question is how do I get the top line in my output to be the same as the sample output?
My procedure is listed below
Declare
#XML_1 varchar (max),
#myXML varchar(max),
#myFile varchar (30),
#Path varchar (100)
set #XML_1=''
set #myFile ='MaterialIssuesTest.xml'
set #Path='D:\Temp\'
--Query database for materials
Set #XML_1 =#XML_1 + ( SELECT WJM.[Job]
,Case when WJM.[Warehouse]='**' then 'Y' else 'N' end as NonStocked
,WJM.[Warehouse]
,rtrim(LP.StockCode) as StockCode
,WJM.[Line]
,[UnitQtyReqd]*LP.LQtyComplete as QuantityToIssue
FROM [SysproCompanyR].[dbo].[WipJobAllMat] WJM
inner join CHC_Production.LabPostsAtMileOps LP On WJM.Job=LP.Job
Where WJM.Job in ('00044816')and (WJM.OperationOffset > LP.PrevOp
and WJM.OperationOffset<LP.LOperation)
FOR XML Path ('Item'),ROOT ('IssueDetails'), ELEMENTS XSINIL
)
set #myXML = LTRIM(rtrim(#XML_1))
--Debug print xml
Print #myXML
--Output xml to document
execute dbo.spWriteStringToFile #myXML, #Path, #myFile
GO
To get you first line, which is a child element of the main body you need to do a sub query like what I have done below. To get the attributes you need to name them with the # symbol, again in my example (formatting changes to aid me setting it out!):
SET #XML_1 =#XML_1 +
(
SELECT WJM.[Job],
(
SELECT '' AS '#Language',
'' AS '#CssStyle',
'' AS '#DecFormat',
'' AS '#DateFormat',
'' AS '#Role',
'' AS '#Version'
FROM YOURTABLENAME YTN
WHERE YTN.[SOMEFIELD] = WJM.[SOMEFIELD]
FOR XML PATH(''), TYPE
) AS 'IssueDetails'
,Case when WJM.[Warehouse]='**' then 'Y' else 'N' end as NonStocked
,WJM.[Warehouse]
,rtrim(LP.StockCode) as StockCode
,WJM.[Line]
,[UnitQtyReqd]*LP.LQtyComplete as QuantityToIssue
FROM [SysproCompanyR].[dbo].[WipJobAllMat] WJM
INNER JOIN CHC_Production.LabPostsAtMileOps LP ON WJM.Job = LP.Job
WHERE WJM.Job IN ('00044816') AND (WJM.OperationOffset > LP.PrevOp
AND WJM.OperationOffset<LP.LOperation)
FOR XML Path ('Item'), ROOT ('IssueDetails'), ELEMENTS XSINIL
)
I don't know where the data is coming from, so you will have to fill in the table name and the WHERE clause to join it to the data that you already have. That is assuming the data is a child of the data that you have already provided.
Bare in mind the syntax might not be quite correct as I am doing this from memory and there are several different variations to get this result.

extract datav values for XML column with XML namespaces in SQL Server

Can anybody please help me with the below xml. I need extract all the xml values like below.
AwarYear Comments FieldCode FieldNumber Key Value
AY2013-14 AAI: Adjusted Available Income AAI 306 Blank None Calculated
Here is the sample XML.
<SchemaType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/process">
<AwardYear>AY2013_14</AwardYear>
<Fields>
<FieldSchema>
<Comments>AAI: Adjusted Available Income</Comments>
<DbLocation>IsirData</DbLocation>
<FieldCode>AAI</FieldCode>
<FieldNumber>306</FieldNumber>
<ReportDisplay>Data</ReportDisplay>
<ValidContent>
<ValidValueContent xmlns:d5p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d5p1:KeyValueOfstringstring>
<d5p1:Key>Blank</d5p1:Key>
<d5p1:Value>None calculated</d5p1:Value>
</d5p1:KeyValueOfstringstring>
</ValidValueContent>
</ValidContent>
</FieldSchema>
</Fields>
</SchemaType>
Please do the need full. Thanks in advance.
Assuming you have your XML in a table inside an XML column like this:
DECLARE #XmlTable TABLE (ID INT NOT NULL, XMLDATA XML)
INSERT INTO #XmlTable VALUES(1, '<SchemaType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/process">
<AwardYear>AY2013_14</AwardYear>
<Fields>
<FieldSchema>
<Comments>AAI: Adjusted Available Income</Comments>
<DbLocation>IsirData</DbLocation>
<FieldCode>AAI</FieldCode>
<FieldNumber>306</FieldNumber>
<ReportDisplay>Data</ReportDisplay>
<ValidContent>
<ValidValueContent xmlns:d5p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d5p1:KeyValueOfstringstring>
<d5p1:Key>Blank</d5p1:Key>
<d5p1:Value>None calculated</d5p1:Value>
</d5p1:KeyValueOfstringstring>
</ValidValueContent>
</ValidContent>
</FieldSchema>
</Fields>
</SchemaType>')
then you can use this T-SQL statement to fetch the values:
;WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/process',
'http://schemas.microsoft.com/2003/10/Serialization/Arrays' AS ns1)
SELECT
AwardYear = XmlData.value('(SchemaType/AwardYear)[1]', 'varchar(25)'),
Comments = XmlData.value('(SchemaType/Fields/FieldSchema/Comments)[1]', 'varchar(50)'),
FieldCode = XmlData.value('(SchemaType/Fields/FieldSchema/FieldCode)[1]', 'varchar(10)'),
FieldNumber = XmlData.value('(SchemaType/Fields/FieldSchema/FieldNumber)[1]', 'int'),
[Key] = XmlData.value('(SchemaType/Fields/FieldSchema/ValidContent/ValidValueContent/ns1:KeyValueOfstringstring/ns1:Key)[1]', 'varchar(10)'),
[Value] = XmlData.value('(SchemaType/Fields/FieldSchema/ValidContent/ValidValueContent/ns1:KeyValueOfstringstring/ns1:Value)[1]', 'varchar(10)')
FROM
#XmlTable
I defined the top-level XML namespace as the "default" namespace (that doesn't need to be referenced all over the place), and the second namespace deep inside your structure is defined explicitly with a separate XML namespace prefix.

Getting the value of dc:creator using SQL XML

I am unsure how to get the value of dc:creator from an RSS-feed using SQL.
This is my xml/rss-feed:
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
<channel>
<title>Foobar RSS</title>
<link>http://www.foobar.com/</link>
<description>RSS feed</description>
<language>en</language>
<ttl>15</ttl>
<item>
<title>This is my title</title>
<link>http://www.foobar.com/link/blabla</link>
<description>Bla..bla..bla..</description>
<dc:creator>John Doe</dc:creator>
<guid isPermaLink="false">00082EA751F1D905DE00E7CFA2417DA9</guid>
<pubDate>Wed, 26 Oct 2011 00:00:00 +0200</pubDate>
</item>
</channel>
</rss>
In my SQL I use something like this to get the values - e.g for pubDate I use something like this:
DECLARE #xml XML
SET #xml = cast('my rss feed here' AS xml)
SELECT
convert(datetime,substring(T.nref.value('pubDate[1]','nvarchar(100)'),6,20)) as pubdate,
FROM #xml.nodes('//item') AS T(nref)
This works fine, but when I am trying to get dc:creator value 'John Doe', the following just gives me an error:
SELECT
T.nref.value('dc:creator','nvarchar(100)') as creator
FROM #xml.nodes('//item') AS T(nref)
error:
XQuery [value()]: The name "dc" does not denote a namespace.
I need to be able to select multiple columns from the rss-feed. Can anybody provide a solution or direction to get the value of dc:creator?
I have another question - how would you construct the code if you are doing it in a sub select?
E.g.
INSERT INTO RSSResults (ID, pubDate)
SELECT #ID, tbl.pubDate FROM (
;WITH XMLNAMESPACES('http://purl.org/dc/elements/1.1/' AS dc)
SELECT
RSS.Item.value('(dc:creator)[1]', 'nvarchar(100)') as pubDate
FROM
#xml.nodes('/rss/channel/item') as RSS(Item)) AS tbl
The code breaks at ";WITH XMLNAMESPACES". Is it possible to include the namespace directly in the statement somehow?
Try something like this:
DECLARE #xml XML
SET #xml = cast('my rss feed here' AS xml)
;WITH XMLNAMESPACES('http://purl.org/dc/elements/1.1/' AS dc)
SELECT
#xml.value('(rss/channel/item/dc:creator)[1]', 'nvarchar(100)')
If you need to catch multiple items - try this:
DECLARE #xml XML
SET #xml = cast('my rss feed here' AS xml)
;WITH XMLNAMESPACES('http://purl.org/dc/elements/1.1/' AS dc)
SELECT
RSS.Item.value('(dc:creator)[1]', 'nvarchar(100)')
FROM
#xml.nodes('/rss/channel/item') as RSS(Item)