Using 2 CROSS APPLY in XML - sql

I'm using below XML to fetch the ClauseCode but it's not returning any data for the below query.
<Policy>
<Plans>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>3</ClauseCode>
</ProductEndorsementClauses>
</Plan>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>1</ClauseCode>
<ClauseCode>2</ClauseCode>
</ProductEndorsementClauses>
</Plan>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>5</ClauseCode>
<ClauseCode>4</ClauseCode>
</ProductEndorsementClauses>
</Plan>
</Plans>
</Policy>
Here is my query :
select proposaid,
,Col1.value('(/*/ProductEndorsementClauses/ClauseCode)[1]','nvarchar(max)')
from Policy p
CROSS APPLY data.nodes('/*/Plans/Plan') AS Tbl(Col)
CROSS APPLY Tbl.Col.nodes('/ProductEndorsementClauses/ClauseCode') AS TblPec(Col1)
where Col1.value('(ProductEndorsementClauses/ClauseCode)[1]', 'nvarchar(max)') in ('1','3')

For inspiration:
declare #x xml = N'
<Policy>
<Plans>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>3</ClauseCode>
</ProductEndorsementClauses>
</Plan>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>1</ClauseCode>
<ClauseCode>2</ClauseCode>
</ProductEndorsementClauses>
</Plan>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>5</ClauseCode>
<ClauseCode>4</ClauseCode>
</ProductEndorsementClauses>
</Plan>
</Plans>
</Policy>'
select #x
--all clause code values
select t.col.value('.[1]', 'nvarchar(10)')
from #x.nodes('Policy/Plans/Plan/ProductEndorsementClauses/ClauseCode') as t(col);
--only clause code values that have at least a 1, 3 clause code in their parent ProductEndorsementClauses
select t.col.value('.[1]', 'nvarchar(10)')
from #x.nodes('Policy/Plans/Plan/ProductEndorsementClauses[(./ClauseCode/text() = "1") or (./ClauseCode/text() = "3")]/ClauseCode') as t(col);
--result only when exists at least a 1 or 3
select t.col.value('.[1]', 'nvarchar(max)')
from #x.nodes('Policy/Plans/Plan/ProductEndorsementClauses/ClauseCode') as t(col)
where #x.exist('Policy/Plans/Plan/ProductEndorsementClauses/ClauseCode[text() = "1" or text() = "3"]') = 1;
declare #Policy table
(
proposaid int,
data xml
);
insert into #Policy(proposaid, data)
values(1, N'
<Policy>
<Plans>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>3</ClauseCode>
</ProductEndorsementClauses>
</Plan>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>1</ClauseCode>
<ClauseCode>2</ClauseCode>
</ProductEndorsementClauses>
</Plan>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>5</ClauseCode>
<ClauseCode>4</ClauseCode>
</ProductEndorsementClauses>
</Plan>
</Plans>
</Policy>'),
(2, N'
<Policy>
<Plans>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>13</ClauseCode>
</ProductEndorsementClauses>
</Plan>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>11</ClauseCode>
<ClauseCode>12</ClauseCode>
</ProductEndorsementClauses>
</Plan>
<Plan>
<ProductEndorsementClauses>
<ClauseCode>15</ClauseCode>
<ClauseCode>14</ClauseCode>
</ProductEndorsementClauses>
</Plan>
</Plans>
</Policy>');
select *
from #Policy;
select p.proposaid,
t.col.value('.[1]', 'nvarchar(max)')
from #Policy as p
cross apply p.data.nodes('Policy/Plans/Plan/ProductEndorsementClauses/ClauseCode') as t(col)
where p.data.exist('Policy/Plans/Plan/ProductEndorsementClauses/ClauseCode[text() = "1" or text() = "3"]') = 1;

Related

XML select and update

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns4:EligibilityRequest xmlns:ns1="http://newmmis.eohhs.ma.gov/serviceobjects/versions/1.0/mmiscommon" xmlns:ns4="http://newmmis.eohhs.ma.gov/serviceobjects/versions/1.0/eligrequest" xmlns:ns3="http://xmlns.eohhs.ma.gov/newMMIS/ws/2006/05/MemberInfo" xmlns:ns5="http://newmmis.eohhs.ma.gov/serviceobjects/versions/1.0/eligresponse">
<ns4:transactionsource id_source="HIX" id_other="00000004353" id_medicaid="100208425271"/>
<ns4:demographic cde_born_to_st_empl=" " cde_born_to_ma=" " ind_pregnancy=" " pct_income_fpl="125" amt_income_fpl="1556.57" amt_indv_income="1638.5" amt_indv_prem="0" mail_adr_zip_code="02532" mail_adr_state="MA" mail_adr_city="Boston" mail_adr_street_2="APT 56" mail_adr_street_1="112 Main ST" res_adr_zip_code="02532" res_adr_state="MA" res_adr_city="Boston" res_adr_street_2="APT 56" res_adr_street_1="112 Main ST" nam_first="John" nam_last="Father" email="MAMedicaid01#hcentive.com" num_phone_day="8575550056" cde_lang_written="RUSSIN" cde_primary_lang="RUSSIN" cde_disability_stat=" " cde_homeless="N" cde_ethnicity="UNKNOW" cde_race="UNKNOW" cde_citizen="C" num_primary_ssn="278938115" cde_sex="M" dte_birth="1978-09-09"/>
<ns4:case amt_family_prem_assist="0" amt_family_mh_prem="0" amt_family_prem="0" hoh_nam_last="Father" hoh_nam_first="John" cde_case_status="2" num_case="00003235C"/>
<ns4:eligibility cde_office="555" cde_region="58" dte_appl="2014-11-13" family_size="2" amt_gross_income="1556.57" cde_cat="D1" cde_elig_status="4" cde_line="00" dte_end_elig="2014-11-13" dte_begin_elig="2014-11-03"/>
<ns4:eligibility cde_open_reason="01" cde_office="555" cde_region="58" dte_appl="2014-11-13" family_size="2" amt_gross_income="1556.57" cde_cat="D1" cde_elig_status="1" cde_line="00" dte_begin_elig="2014-11-03"/>
</ns4:EligibilityRequest>
If you open this attached XML, you can see there is 2 tags of <ns4:eligibility
I have to first select this last sub string, either by regexp_substr or simple str .. means output should be:
<ns4:eligibility cde_open_reason="01" cde_office="555" cde_region="58" dte_appl="2014-11-13" family_size="2" amt_gross_income="1556.57" cde_cat="D1" cde_elig_status="1" cde_line="00" dte_begin_elig="2014-11-03"/>
Then append this string to another xml. same like this. just append in last.
Oracle Setup:
CREATE TABLE XML_IN ( id INT, xml CLOB );
INSERT INTO XML_IN VALUES ( 1, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns4:EligibilityRequest xmlns:ns1="http://newmmis.eohhs.ma.gov/serviceobjects/versions/1.0/mmiscommon" xmlns:ns4="http://newmmis.eohhs.ma.gov/serviceobjects/versions/1.0/eligrequest" xmlns:ns3="http://xmlns.eohhs.ma.gov/newMMIS/ws/2006/05/MemberInfo" xmlns:ns5="http://newmmis.eohhs.ma.gov/serviceobjects/versions/1.0/eligresponse">
<ns4:transactionsource id_source="HIX" id_other="00000004353" id_medicaid="100208425271"/>
<ns4:demographic cde_born_to_st_empl=" " cde_born_to_ma=" " ind_pregnancy=" " pct_income_fpl="125" amt_income_fpl="1556.57" amt_indv_income="1638.5" amt_indv_prem="0" mail_adr_zip_code="02532" mail_adr_state="MA" mail_adr_city="Boston" mail_adr_street_2="APT 56" mail_adr_street_1="112 Main ST" res_adr_zip_code="02532" res_adr_state="MA" res_adr_city="Boston" res_adr_street_2="APT 56" res_adr_street_1="112 Main ST" nam_first="John" nam_last="Father" email="MAMedicaid01#hcentive.com" num_phone_day="8575550056" cde_lang_written="RUSSIN" cde_primary_lang="RUSSIN" cde_disability_stat=" " cde_homeless="N" cde_ethnicity="UNKNOW" cde_race="UNKNOW" cde_citizen="C" num_primary_ssn="278938115" cde_sex="M" dte_birth="1978-09-09"/>
<ns4:case amt_family_prem_assist="0" amt_family_mh_prem="0" amt_family_prem="0" hoh_nam_last="Father" hoh_nam_first="John" cde_case_status="2" num_case="00003235C"/>
<ns4:eligibility cde_office="555" cde_region="58" dte_appl="2014-11-13" family_size="2" amt_gross_income="1556.57" cde_cat="D1" cde_elig_status="4" cde_line="00" dte_end_elig="2014-11-13" dte_begin_elig="2014-11-03"/>
<ns4:eligibility cde_open_reason="01" cde_office="555" cde_region="58" dte_appl="2014-11-13" family_size="2" amt_gross_income="1556.57" cde_cat="D1" cde_elig_status="1" cde_line="00" dte_begin_elig="2014-11-03"/>
</ns4:EligibilityRequest>');
CREATE TABLE XML_OUT( id INT, xml CLOB );
INSERT INTO XML_OUT VALUES ( 1, '<test><attribute>existing</attribute></test>' );
Query:
MERGE INTO XML_OUT o
USING XML_IN i ON ( o.id = i.id )
WHEN MATCHED THEN
UPDATE
SET xml = APPENDCHILDXML(
XMLType( o.xml ),
'/test',
EXTRACT(
XMLType( i.xml ),
'//ns4:EligibilityRequest/ns4:eligibility[last()]',
'xmlns:ns4="http://newmmis.eohhs.ma.gov/serviceobjects/versions/1.0/eligrequest"'
)
).getClobVal();
Output:
SELECT * FROM XML_OUT;
ID XML
---------- ----------------------------------------------------------------------
1 <test><attribute>existing</attribute><ns4:eligibility xmlns:ns4="http:
//newmmis.eohhs.ma.gov/serviceobjects/versions/1.0/eligrequest" cde_ope
n_reason="01" cde_office="555" cde_region="58" dte_appl="2014-11-13" fa
mily_size="2" amt_gross_income="1556.57" cde_cat="D1" cde_elig_status="
1" cde_line="00" dte_begin_elig="2014-11-03"/></test>

Parsing XML by OpenXML with multiple Parent nodes with multiple child nodes

I have the following XML:
<Report>
<Accounts>
<Account>
<Currency>USD</Currency>
<AccountBalance>45555</AccountBalance>
<Payments>
<PaymentData>
<PaymentCode>502</PaymentCode>
<PaymentAmount currCode="GBP">7000.00000000</PaymentAmount>
</PaymentData>
<PaymentData>
<PaymentCode>501</PaymentCode>
<PaymentAmount currCode="USD">5000.00000000</PaymentAmount>
</PaymentData>
</Payments>
</Account>
<Account>
<Currency>USD</Currency>
<AccountBalance>50000</AccountBalance>
<Payments>
<PaymentData>
<PaymentCode>501</PaymentCode>
<PaymentAmount currCode="USD">5000.00000000</PaymentAmount>
</PaymentData>
</Payments>
</Account>
</Accounts>
</Report>
My SQL Code is parsing this with the following code:
SELECT
[currCode] AS [Currency],
[AccountBalance] AS [AccountBalance],
[PaymentCode] AS [PaymentCode],
[PaymentCurrCode] AS [PaymentCurrCode],
[PaymentAmount] AS [PaymentAmount]
FROM OPENXML(#hDoc, 'Report/Accounts/Account',2)
WITH
(
[currCode] [nchar](3) 'currCode',
[AccountBalance] [decimal](18, 0) 'AccountBalance',
[PaymentCode] [nchar](10) 'Payments/PaymentData/PaymentCode',
[PaymentCurrCode] [nchar](3) 'Payments/PaymentData/PaymentAmount/#currCode',
[PaymentAmount] [decimal](18, 0) 'Payments/PaymentData/PaymentAmount'
)
I am getting the following result:
currCode | AccountBalance | PaymentCode | PaymentCurrCode | PaymentAmount
————————————————————————————————————————————————————————————————————————————————
USD | 45555 | 502 | GBP |7000.00000000
USD | 50000 | 501 | USD |5000.00000000
I am trying to get the multiple paymentdata and multiple account with the same openXml query. How Can is get all the data with the following result:
currCode | AccountBalance | PaymentCode | PaymentCurrCode | PaymentAmount
————————————————————————————————————————————————————————————————————————————————
USD | 45555 | 502 | GBP |7000.00000000
USD | 45555 | 501 | USD |5000.00000000
USD | 50000 | 501 | USD |5000.00000000
This is an up-to-date and state-of-the-art approach with XQuery/XPath methods. The result is the same, just faster and better to read:
DECLARE #XML XML=
'<Report>
<Accounts>
<Account>
<Currency>USD</Currency>
<AccountBalance>45555</AccountBalance>
<Payments>
<PaymentData>
<PaymentCode>502</PaymentCode>
<PaymentAmount currCode="GBP">7000.00000000</PaymentAmount>
</PaymentData>
<PaymentData>
<PaymentCode>501</PaymentCode>
<PaymentAmount currCode="USD">5000.00000000</PaymentAmount>
</PaymentData>
</Payments>
</Account>
<Account>
<Currency>USD</Currency>
<AccountBalance>50000</AccountBalance>
<Payments>
<PaymentData>
<PaymentCode>501</PaymentCode>
<PaymentAmount currCode="USD">5000.00000000</PaymentAmount>
</PaymentData>
</Payments>
</Account>
</Accounts>
</Report>';
SELECT Payment.value('(../../Currency)[1]','nchar(3)') AS currCode
,Payment.value('(../../AccountBalance)[1]','decimal(18,0)') AS AccountBalance
,Payment.value('PaymentCode[1]','nchar(10)') AS PaymentCode
,Payment.value('PaymentAmount[1]/#currCode','nchar(3)') AS PaymentCurrCode
,Payment.value('PaymentAmount[1]','decimal(18,0)') AS PaymentCurrCode
FROM #XML.nodes('Report/Accounts/Account/Payments/PaymentData') AS One(Payment)
This should work for you:
DECLARE #XML XML=
'<Report>
<Accounts>
<Account>
<Currency>USD</Currency>
<AccountBalance>45555</AccountBalance>
<Payments>
<PaymentData>
<PaymentCode>502</PaymentCode>
<PaymentAmount currCode="GBP">7000.00000000</PaymentAmount>
</PaymentData>
<PaymentData>
<PaymentCode>501</PaymentCode>
<PaymentAmount currCode="USD">5000.00000000</PaymentAmount>
</PaymentData>
</Payments>
</Account>
<Account>
<Currency>USD</Currency>
<AccountBalance>50000</AccountBalance>
<Payments>
<PaymentData>
<PaymentCode>501</PaymentCode>
<PaymentAmount currCode="USD">5000.00000000</PaymentAmount>
</PaymentData>
</Payments>
</Account>
</Accounts>
</Report>';
DECLARE #hDoc INT;
EXEC sp_xml_preparedocument #hDoc OUTPUT, #XML;
SELECT
[currCode] AS [Currency],
[AccountBalance] AS [AccountBalance],
[PaymentCode] AS [PaymentCode],
[PaymentCurrCode] AS [PaymentCurrCode],
[PaymentAmount] AS [PaymentAmount]
FROM OPENXML(#hDoc, 'Report/Accounts/Account/Payments/PaymentData',2)
WITH
(
[currCode] [nchar](3) '../../Currency',
[AccountBalance] [decimal](18, 0) '../../AccountBalance',
[PaymentCode] [nchar](10) 'PaymentCode',
[PaymentCurrCode] [nchar](3) 'PaymentAmount/#currCode',
[PaymentAmount] [decimal](18, 0) 'PaymentAmount'
)
EXEC sp_xml_removedocument #hDoc;

EXTRACT RESULTS FROM XML node with namespace using SQL

I Have the below XML and want to extract the values for the following Nodes
1. result
2. documentNumber
3. costElementCode
<commitmentsResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<result xmlns="http://response.cim.its.test.edu.au/">SUCCESS</result>
<value xmlns="http://finance.response.cim.its.test.edu.au/">
<documentNumber xmlns="http://finance.cim.its.test.edu.au/">12345</documentNumber>
<lineNumber>2</lineNumber>
<costElementCode>costElementCode</costElementCode>
<internalOrderNumber>1000002</internalOrderNumber>
<costCentreCode>9999</costCentreCode>
<wbsCode>3000</wbsCode>
<lineDescription>2 packets of pencils</lineDescription>
<accountNumber>100000</accountNumber>
<itemAmount>105.5</itemAmount>
<fundsDueDate>2015-06-15</fundsDueDate>
</commitmentLine>
<commitmentLine xmlns="http://finance.cim.its.test.edu.au/">
<lineNumber>2</lineNumber>
<costElementCode>costElementCode</costElementCode>
<internalOrderNumber>1000002</internalOrderNumber>
<costCentreCode>9999</costCentreCode>
<wbsCode>3000</wbsCode>
<lineDescription>2 packets of pencils</lineDescription>
<accountNumber>100000</accountNumber>
<itemAmount>105.5</itemAmount>
<fundsDueDate>2015-06-15</fundsDueDate>
</commitmentLine>
</value>
</commitmentsResponse>
Without using Namespaces:
DECLARE #myXML xml =
N'<commitmentsResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<result>SUCCESS</result>
<value>
<documentNumber>12345</documentNumber>
<commitmentLine>
<lineNumber>2</lineNumber>
<costElementCode>costElementCode</costElementCode>
<internalOrderNumber>1000002</internalOrderNumber>
<costCentreCode>9999</costCentreCode>
<wbsCode>3000</wbsCode>
<lineDescription>2 packets of pencils</lineDescription>
<accountNumber>100000</accountNumber>
<itemAmount>105.5</itemAmount>
<fundsDueDate>2015-06-15</fundsDueDate>
</commitmentLine>
<commitmentLine xmlns="http://finance.cim.its.test.edu.au/">
<lineNumber>2</lineNumber>
<costElementCode>costElementCode</costElementCode>
<internalOrderNumber>1000002</internalOrderNumber>
<costCentreCode>9999</costCentreCode>
<wbsCode>3000</wbsCode>
<lineDescription>2 packets of pencils</lineDescription>
<accountNumber>100000</accountNumber>
<itemAmount>105.5</itemAmount>
<fundsDueDate>2015-06-15</fundsDueDate>
</commitmentLine>
</value>
</commitmentsResponse>'
DECLARE #DocumentNumber INT
SELECT #DocumentNumber = [Table].[Column].value('documentNumber[1]', 'INT')
FROM #myXML.nodes('/commitmentsResponse/value') AS [Table]([Column])
DECLARE #Result VARCHAR(256)
SELECT #Result = [Table].[Column].value('result[1]', 'varchar(256)')
FROM #myXML.nodes('/commitmentsResponse') AS [Table]([Column])
DECLARE #CostElementCode VARCHAR(256)
SELECT #CostElementCode = [Table].[Column].value('costElementCode[1]', 'varchar(256)')
FROM #myXML.nodes('/commitmentsResponse/value/commitmentLine') AS [Table]([Column])
SELECT #Result
SELECT #DocumentNumber
SELECT #CostElementCode
With using namespaces:
DECLARE #myXML xml =
N'<commitmentsResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<result xmlns="http://response.cim.its.test.edu.au/">SUCCESS</result>
<value>
<documentNumber xmlns="http://finance.cim.its.test.edu.au/">12345</documentNumber>
<commitmentLine>
<lineNumber>2</lineNumber>
<costElementCode>costElementCode</costElementCode>
<internalOrderNumber>1000002</internalOrderNumber>
<costCentreCode>9999</costCentreCode>
<wbsCode>3000</wbsCode>
<lineDescription>2 packets of pencils</lineDescription>
<accountNumber>100000</accountNumber>
<itemAmount>105.5</itemAmount>
<fundsDueDate>2015-06-15</fundsDueDate>
</commitmentLine>
<commitmentLine xmlns="http://finance.cim.its.test.edu.au/">
<lineNumber>2</lineNumber>
<costElementCode>costElementCode</costElementCode>
<internalOrderNumber>1000002</internalOrderNumber>
<costCentreCode>9999</costCentreCode>
<wbsCode>3000</wbsCode>
<lineDescription>2 packets of pencils</lineDescription>
<accountNumber>100000</accountNumber>
<itemAmount>105.5</itemAmount>
<fundsDueDate>2015-06-15</fundsDueDate>
</commitmentLine>
</value>
</commitmentsResponse>'
DECLARE #DocumentNumber INT
;WITH XMLNAMESPACES (N'http://finance.cim.its.test.edu.au/' as DYN)
SELECT #DocumentNumber = c.value('(DYN:documentNumber)[1]', 'INT')
FROM #myXML.nodes('/commitmentsResponse/value') t(c)
DECLARE #Result VARCHAR(256)
;WITH XMLNAMESPACES (N'http://response.cim.its.test.edu.au/' as DYN)
SELECT #Result = c.value('(DYN:result)[1]', 'VARCHAR(256)')
FROM #myXML.nodes('/commitmentsResponse') t(c)
DECLARE #CostElementCode VARCHAR(256)
SELECT #CostElementCode = c.value('(costElementCode)[1]', 'VARCHAR(256)')
FROM #myXML.nodes('/commitmentsResponse/value/commitmentLine') t(c)
SELECT #Result
SELECT #DocumentNumber
SELECT #CostElementCode

How can I save data from xml to sql 2008?

How can I save data from xml to sql 2008?
SQL table:
[dbo].[Position](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ImoNo] [numeric](8, 0) NOT NULL,
[sid] [numeric](5, 0) NULL,
[VesselName] [nvarchar](20) NULL,
[time] [datetime] NOT NULL,
[lat] [numeric](9, 2) NULL,
[lon] [numeric](9, 2) NULL,
[sog] [numeric](9, 2) NULL,
[cog] [numeric](9, 2) NULL,
[hdg] [numeric](9, 2) NULL,
[eta] [datetime] NULL,
[NextPort] [nvarchar](20) NULL)
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.fleettracker.de/api/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<ns1:GetPositionsResponse>
<body>
<result>Found 2 vessels.</result>
<success>true</success>
<shipsWithPositions xsi:type="ns1:FleettrackerShip">
<ns1:imono>9456159</ns1:imono>
<ns1:sid>780</ns1:sid>
<ns1:name>Trenta</ns1:name>
<ns1:charterShipName>Trenta</ns1:charterShipName>
<ns1:pasttrack>
<lat>1832900</lat>
<lon>7570400</lon>
<timestamp>2014-01-14T08:28:45Z</timestamp>
<orderNumber>0</orderNumber>
<sog>9.5</sog>
<cog>22</cog>
<hdg>22</hdg>
<eta>2014-01-15T12:00:00</eta>
<nextport>KWANGYANG</nextport>
</ns1:pasttrack>
<ns1:pasttrack>
<lat>1872560</lat>
<lon>7589000</lon>
<timestamp>2014-01-14T07:00:00Z</timestamp>
<orderNumber>1</orderNumber>
<sog>10.8</sog>
<cog>25</cog>
<hdg>25</hdg>
</ns1:pasttrack>
</shipsWithPositions>
<shipsWithPositions xsi:type="ns1:FleettrackerShip">
<ns1:imono>9144055</ns1:imono>
<ns1:sid>789</ns1:sid>
<ns1:name>Vipava</ns1:name>
<ns1:charterShipName>Vipava</ns1:charterShipName>
<ns1:pasttrack>
<lat>1757160</lat>
<lon>7536240</lon>
<timestamp>2014-01-13T19:00:00Z</timestamp>
<orderNumber>2</orderNumber>
<sog>9.4</sog>
<cog>21</cog>
<hdg>21</hdg>
</ns1:pasttrack>
<ns1:pasttrack>
<lat>1658200</lat>
<lon>7476480</lon>
<timestamp>2014-01-13T07:00:00Z</timestamp>
<orderNumber>3</orderNumber>
<sog>8.4</sog>
<cog>29</cog>
<hdg>29</hdg>
</ns1:pasttrack>
<ns1:pasttrack>
<lat>1630000</lat>
<lon>7455400</lon>
<timestamp>2014-01-13T03:00:03Z</timestamp>
<orderNumber>4</orderNumber>
<sog>8.83</sog>
<cog>34</cog>
<hdg>34</hdg>
<eta>2014-01-15T08:00:00</eta>
<nextport>KWANGYANG</nextport>
</ns1:pasttrack>
</shipsWithPositions>
</body>
</ns1:GetPositionsResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I tried with this query, but I get error msg
'XQuery [nodes()]: The names "SOAP-ENV" and "ns1:" do not denote a namespace.'
DECLARE #xml XML
DECLARE #character VARCHAR(MAX)
SELECT #character = x.y
FROM OPENROWSET( BULK 'C:\Users\Nale\Desktop\POS.xml', SINGLE_CLOB ) x(y)
-- Fix up the ampersand
SELECT #xml = REPLACE( #character, '&', '&' )
-- Get the tally information
SELECT
x.y.value('ns1:imono/text())[1]', 'NUMERIC (8,0)') ImoNo,
x.y.value('ns1:sid/text())[1]', 'NUMERIC (5,0)') sid,
x.y.value('ns1:VesselName/text())[1]', 'NVARCHAR (20)') VesselName,
x.y.value('ns1:pasttrack/time/text())[1]', 'DATETIME') time,
x.y.value('ns1:pasttrack/lat/text())[1]', 'NUMERIC (9,2)') lat,
x.y.value('ns1:pasttrack/lon/text())[1]', 'NUMERIC (9,2)') lon,
x.y.value('ns1:pasttrack/sog/text())[1]', 'NUMERIC (9,2)') sog,
x.y.value('ns1:pasttrack/cog/text())[1]', 'NUMERIC (9,2)') cog,
x.y.value('ns1:pasttrack/hdg/text())[1]', 'NUMERIC (9,2)') hdg,
x.y.value('ns1:pasttrack/eta/text())[1]', 'DATETIME') eta,
x.y.value('ns1:pasttrack/NextPort/text())[1]', 'NVARCHAR (20)') NextPort
FROM #xml.nodes('SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:GetPositionsResponse/body/shipsWithPositions') AS x(y)
XML file is on local disk.
Will I use some sql query, or what is the best way to save data from xml to sql table?
Make XML valid
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.fleettracker.de/api/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<ns1:GetPositionsResponse>
<body>
<result>Found 2 vessels.</result>
<success>true</success>
<shipsWithPositions xsi:type="ns1:FleettrackerShip">
<ns1:imono>9456159</ns1:imono>
<ns1:sid>780</ns1:sid>
<ns1:name>Trenta</ns1:name>
<ns1:charterShipName>Trenta</ns1:charterShipName>
<ns1:pasttrack>
<lat>1832900</lat>
<lon>7570400</lon>
<timestamp>2014-01-14T08:28:45Z</timestamp>
<orderNumber>0</orderNumber>
<sog>9.5</sog>
<cog>22</cog>
<hdg>22</hdg>
<eta>2014-01-15T12:00:00</eta>
<nextport>KWANGYANG</nextport>
</ns1:pasttrack>
<ns1:pasttrack>
<lat>1872560</lat>
<lon>7589000</lon>
<timestamp>2014-01-14T07:00:00Z</timestamp>
<orderNumber>1</orderNumber>
<sog>10.8</sog>
<cog>25</cog>
<hdg>25</hdg>
</ns1:pasttrack>
</shipsWithPositions>
<shipsWithPositions xsi:type="ns1:FleettrackerShip">
<ns1:imono>9144055</ns1:imono>
<ns1:sid>789</ns1:sid>
<ns1:name>Vipava</ns1:name>
<ns1:charterShipName>Vipava</ns1:charterShipName>
<ns1:pasttrack>
<lat>1757160</lat>
<lon>7536240</lon>
<timestamp>2014-01-13T19:00:00Z</timestamp>
<orderNumber>2</orderNumber>
<sog>9.4</sog>
<cog>21</cog>
<hdg>21</hdg>
</ns1:pasttrack>
<ns1:pasttrack>
<lat>1658200</lat>
<lon>7476480</lon>
<timestamp>2014-01-13T07:00:00Z</timestamp>
<orderNumber>3</orderNumber>
<sog>8.4</sog>
<cog>29</cog>
<hdg>29</hdg>
</ns1:pasttrack>
<ns1:pasttrack>
<lat>1630000</lat>
<lon>7455400</lon>
<timestamp>2014-01-13T03:00:03Z</timestamp>
<orderNumber>4</orderNumber>
<sog>8.83</sog>
<cog>34</cog>
<hdg>34</hdg>
<eta>2014-01-15T08:00:00</eta>
<nextport>KWANGYANG</nextport>
</ns1:pasttrack>
</shipsWithPositions>
</body>
</ns1:GetPositionsResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
2. Add namespaces to your query
DECLARE #xml XML
DECLARE #character VARCHAR(MAX)
SELECT #xml = x.y
FROM OPENROWSET( BULK 'C:\Users\Nale\Desktop\POS.xml', SINGLE_CLOB ) x(y)
-- Get the tally information
;WITH XMLNAMESPACES (
'http://www.fleettracker.de/api/1.0' as ns1,
'http://www.w3.org/2001/XMLSchema-instance' AS xsi,
'http://schemas.xmlsoap.org/soap/envelope/' AS e
)
SELECT
x.y.value('(ns1:imono/text())[1]', 'NUMERIC (8,0)') ImoNo,
x.y.value('(ns1:sid/text())[1]', 'NUMERIC (5,0)') sid,
x.y.value('(ns1:VesselName/text())[1]', 'NVARCHAR (20)') VesselName,
x.y.value('(ns1:pasttrack/time/text())[1]', 'DATETIME') time,
x.y.value('(ns1:pasttrack/lat/text())[1]', 'NUMERIC (9,2)') lat,
x.y.value('(ns1:pasttrack/lon/text())[1]', 'NUMERIC (9,2)') lon,
x.y.value('(ns1:pasttrack/sog/text())[1]', 'NUMERIC (9,2)') sog,
x.y.value('(ns1:pasttrack/cog/text())[1]', 'NUMERIC (9,2)') cog,
x.y.value('(ns1:pasttrack/hdg/text())[1]', 'NUMERIC (9,2)') hdg,
x.y.value('(ns1:pasttrack/eta/text())[1]', 'DATETIME') eta,
x.y.value('(ns1:pasttrack/NextPort/text())[1]', 'NVARCHAR (20)') NextPort
FROM #xml.nodes('e:Envelope/e:Body/ns1:GetPositionsResponse/body/shipsWithPositions') AS x(y)

xml file data imported to sql with script

im having this kind of xml:
<?xml version="1.0"?>
-<recordedData>
<machine>ZSK40-2</machine>
<date>2013/09/21</date>
<hour>05:32</hour>-<CollectedData>-<variable>
<Name>PRODUCT</Name>
<Value>FILLER 580</Value>
</variable>-<variable>
<Name>LOT_NUMBER</Name>
<Value>CG 00063 0</Value>
</variable>-<variable>
<Name>SHIFT_SUPERVISOR</Name>
<Value> covaliu l</Value>
</variable>-<variable>
<Name>KGH_ALL_SET</Name>
<Value>0</Value>
</variable>-<variable>
<Name>KGH_ALL_REAL</Name>
<Value>0</Value>
</variable>-<variable>
<Name>KGH_F1_SET</Name>
<Value>0</Value>
</variable>-<variable>
<Name>KGH_F1_REAL</Name>
<Value>0</Value>
</variable>-<variable>
<Name>K_F1</Name>
<Value>43</Value>
</variable>-<variable>
<Name>SCREW_RPM_SET</Name>
<Value>550</Value>
</variable>-<variable>
<Name>SCREW_RPM_REAL</Name>
<Value>550.085388183594</Value>
</variable>-<variable>
<Name>TORQUE</Name>
<Value>1.21340000629425</Value>
</variable>-<variable>
<Name>CURRENT</Name>
<Value>60.1959991455078</Value>
</variable>-<variable>
<Name>KW_KG</Name>
<Value>0</Value>
</variable>-<variable>
<Name>KW</Name>
<Value>-0.990000009536743</Value>
</variable>-<variable>
<Name>MELT_PRESSURE</Name>
<Value>0</Value>
</variable>-<variable>
<Name>MELT_TEMPERATURE</Name>
<Value>214</Value>
</variable>-<variable>
<Name>PV1</Name>
<Value>216</Value>
</variable>-<variable>
<Name>SP1</Name>
<Value>210</Value>
</variable>-<variable>
<Name>PV2</Name>
<Value>239</Value>
</variable>-<variable>
<Name>SP2</Name>
<Value>220</Value>
</variable>-<variable>
<Name>PV3</Name>
<Value>220</Value>
</variable>-<variable>
<Name>SP3</Name>
<Value>220</Value>
</variable>-<variable>
<Name>PV4</Name>
<Value>220</Value>
</variable>-<variable>
<Name>SP4</Name>
<Value>220</Value>
</variable>-<variable>
<Name>PV5</Name>
<Value>209</Value>
</variable>-<variable>
<Name>SP5</Name>
<Value>210</Value>
</variable>-<variable>
<Name>PV6</Name>
<Value>210</Value>
</variable>-<variable>
<Name>SP6</Name>
<Value>210</Value>
</variable>-<variable>
<Name>PV7</Name>
<Value>210</Value>
</variable>-<variable>
<Name>SP7</Name>
<Value>210</Value>
</variable>-<variable>
<Name>PV8</Name>
<Value>210</Value>
</variable>-<variable>
<Name>SP8</Name>
<Value>210</Value>
</variable>-<variable>
<Name>PV9</Name>
<Value>210</Value>
</variable>-<variable>
<Name>SP9</Name>
<Value>210</Value>
</variable>-<variable>
<Name>PV10</Name>
<Value>210</Value>
</variable>-<variable>
<Name>SP10</Name>
<Value>210</Value>
</variable>-<variable>
<Name>PV11</Name>
<Value>220</Value>
</variable>-<variable>
<Name>SP11</Name>
<Value>220</Value>
</variable>
</CollectedData>
</recordedData>
Can anyone provide a sample sql script for extracting all the data from it please.
i would really apreciate this since im new to xml.
Thanks in advance.
If you have your data in a table already, you can use something like this:
DECLARE #Tmp TABLE (ID INT NOT NULL, XmlContent XML)
INSERT INTO #TMP VALUES(1, '......(your entire XML here).......)
SELECT
ID,
MACHINE = XmlContent.value('(/recordedData/machine)[1]', 'varchar(50)'),
RecordingDate = XmlContent.value('(/recordedData/date)[1]', 'varchar(50)'),
RecordingTime = XmlContent.value('(/recordedData/hour)[1]', 'varchar(50)'),
VariableName = XVar.value('(Name)[1]', 'varchar(50)'),
VariableValue = XVar.value('(Value)[1]', 'varchar(50)')
FROM
#Tmp
CROSS APPLY
XmlContent.nodes('/recordedData/CollectedData/variable') AS XTbl(XVar)
This gives you an output something like:
.... and so on - listing all the variables with their name and value.