SQL xml query returns null - sql

I have the following XML:
<Matter>
<CriticalDates>
<CriticalDate>
<CriticalDateId>2</CriticalDateId>
<Name>Instruction Date</Name>
<Value_FieldId>9F21</Value_FieldId>
<Confirmed_FieldId />
<Status>In Progress</Status>
<ConfirmStatus />
<CompPercent>0</CompPercent>
<Order>0</Order>
<Value>2014-03-28T06:00:00+11:00</Value>
<Confirmed>false</Confirmed>
</CriticalDate>
<CriticalDate>
<CriticalDateId>-2</CriticalDateId>
<Name>Completion Date</Name>
<Value_FieldId>9F22</Value_FieldId>
<Confirmed_FieldId>9F27</Confirmed_FieldId>
<Status>Complete</Status>
<ConfirmStatus />
<CompPercent>0</CompPercent>
<Order>1</Order>
<Value />
<Confirmed>false</Confirmed>
</CriticalDate>
<CriticalDate>
<CriticalDateId>-3</CriticalDateId>
<Name>Not Proceeding Date</Name>
<Value_FieldId>9F23</Value_FieldId>
<Confirmed_FieldId />
<Status>Not Proceeding</Status>
<ConfirmStatus />
<CompPercent>0</CompPercent>
<Order>2</Order>
<Value />
<Confirmed>false</Confirmed>
</CriticalDate>
</CriticalDates>
</Matter>
To select all the nodes as rows i'm using:
SELECT
MatterId,
MatterXml,
MD.CD.value('(Name)[1]', 'VARCHAR(50)') AS 'Name',
MD.CD.value('(Status)[1]', 'VARCHAR(50)') AS 'Status',
MD.CD.value('(value)[1]', 'DATE') AS 'CriticalDate',
MD.CD.value('(Confirmed)[1]', 'VARCHAR(50)') AS 'Confirmed'
FROM
dbo.Matter m
CROSS APPLY m.MatterXml.nodes('/Matter/CriticalDates/CriticalDate') AS MD(CD)
When i run this i get 3 rows back but all CriticalDates return as NULL even the first one when there is a date in the XML. Please help!

XML is case sensitive. Try is with:
MD.CD.value('(Value)[1]', 'DATE') AS 'CriticalDate',

Related

loop / Extract nodes from clob xml column in oracle pl sql

I have this xml content stored in a clob column of a table, I have to loop through the "molecule" nodes under the "reactantList" node,and store each "molecule" node into another table containing a list of molecules,
Any help please?
I tried with xmltype, xmlsequence, xmltable etc but did not work, I also have to specify the namespace "xmlns=.." somewhere as an argument to xmltype I think, to be able to make it work...
<cml xmlns="http://www.chemaxon.com" version="ChemAxon file format v20.20.0, generated by vunknown" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.chemaxon.com http://www.chemaxon.com/marvin/schema/mrvSchema_20_20_0.xsd">
<MDocument>
<MChemicalStruct>
<reaction>
<arrow type="DEFAULT" x1="-8.022119140625" y1="0.8333333333333334" x2="-3.5637858072916657" y2="0.8333333333333334" />
<reactantList>
<molecule molID="m1">
<atomArray>
<atom id="a1" elementType="C" x2="-13.938333333333334" y2="0.7083333333333333" />
<atom id="a2" elementType="O" x2="-15.478333333333333" y2="0.7083333333333333" lonePair="2" />
</atomArray>
<bondArray>
<bond id="b1" atomRefs2="a1 a2" order="1" />
</bondArray>
</molecule>
<molecule molID="m2">
<atomArray>
<atom id="a1" elementType="O" x2="-9.897119140624998" y2="0.8333333333333333" mrvValence="0" lonePair="3" />
</atomArray>
<bondArray />
</molecule>
</reactantList>
<agentList />
<productList />
</reaction>
</MChemicalStruct>
<MReactionSign toption="NOROT" fontScale="14.0" halign="CENTER" valign="CENTER" autoSize="true" id="o1">
<Field name="text">
<![CDATA[{D font=SansSerif,size=18,bold}+]]>
</Field>
<MPoint x="-11.730452473958332" y="0.6666666666666666" />
<MPoint x="-11.217119140624998" y="0.6666666666666666" />
<MPoint x="-11.217119140624998" y="1.18" />
<MPoint x="-11.730452473958332" y="1.18" />
</MReactionSign>
</MDocument>
</cml>
You can use:
INSERT INTO molecules (molecule)
SELECT x.molecule
FROM table_name t
CROSS APPLY XMLTABLE(
XMLNAMESPACES(
'http://www.w3.org/2001/XMLSchema-instance' AS "xsi",
DEFAULT 'http://www.chemaxon.com'
),
'/cml/MDocument/MChemicalStruct/reaction/reactantList/molecule'
PASSING XMLTYPE(t.xml)
COLUMNS
molecule XMLTYPE PATH '.'
) x
db<>fiddle here

Extracting data from XML Array using SQL

I have the following XML and would like to extract the PrimaryTeams, SecondaryTeams and OverflowTeams arrays from this and either have them comma separated or one per row.
I have the following xml:
declare #xml xml
set #xml = '<SimpleStrategy xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Synthesys.Switch.ACD">
<Id>00000000-0000-0000-0000-000000000000</Id>
<Name>Default</Name>
<AcceptedCLIs xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>07811353995</d2p1:string>
</AcceptedCLIs>
<ActiveHours>
<FridayEnd />
<FridayStart />
<MondayEnd />
<MondayStart />
<SaturdayEnd />
<SaturdayStart />
<SundayEnd />
<SundayStart />
<ThursdayEnd />
<ThursdayStart />
<TuesdayEnd />
<TuesdayStart />
<UseIndividualWeekDays>false</UseIndividualWeekDays>
<WednesdayEnd />
<WednesdayStart />
<WeekdayEnd />
<WeekdayStart />
</ActiveHours>
<AgentUserName />
<AllowRouteDuringFinalMessage>false</AllowRouteDuringFinalMessage>
<CRMPrefix />
<DirectDDIMessage />
<DirectDDIPassThrough>false</DirectDDIPassThrough>
<EmergencyBusyBack>false</EmergencyBusyBack>
<EmergencyDivertNumber />
<EmergencyWavFile />
<FinallyDivertNumber />
<FinallyDrop>true</FinallyDrop>
<FinallyMessageFile />
<MaximumQueueLength>0</MaximumQueueLength>
<MaximumQueueWait>0</MaximumQueueWait>
<MinimumRingTime>4000</MinimumRingTime>
<MusicOnHold />
<MusicWhileWaiting />
<NumberOfRings>2</NumberOfRings>
<OutOfHoursDivertNumber />
<OutOfHoursDrop>true</OutOfHoursDrop>
<OutOfHoursMessage />
<OverflowMessage />
<OverflowTeams xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
<PrimaryTeams xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:int>3</d2p1:int>
<d2p1:int>1</d2p1:int>
</PrimaryTeams>
<Priority>1</Priority>
<RecordAgent>false</RecordAgent>
<RecordCall>true</RecordCall>
<RecordCustomer>false</RecordCustomer>
<RegulatoryMessage>Default.wav</RegulatoryMessage>
<SecondaryOverflowMessage />
<SecondaryTeams xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
<SendBusyIfQueueTooLong>false</SendBusyIfQueueTooLong>
<SendBusyIfWaitTooLong>false</SendBusyIfWaitTooLong>
<TimeInOverflow>-1</TimeInOverflow>
<TimeWithDirectDDI>20000</TimeWithDirectDDI>
<TimeWithPrimaryTeams>-1</TimeWithPrimaryTeams>
<TimeWithSecondaryTeams>20000</TimeWithSecondaryTeams>
<UseDirectDDI>false</UseDirectDDI>
<UsePAM>false</UsePAM>
<UseSecondaryTeams>false</UseSecondaryTeams>
<WrapTime>40000</WrapTime>
</SimpleStrategy>'
I then created the following SQL Statement to try and extract the Teams
;WITH XMLNAMESPACES ('http://www.w3.org/2001/XMLSchema-instance' as i, 'http://schemas.microsoft.com/2003/10/Serialization/Arrays' as d2p1,
DEFAULT 'http://schemas.datacontract.org/2004/07/Synthesys.Switch.ACD')
SELECT #xml,
#xml.value('(/SimpleStrategy/Name)[1]', 'varchar(255)'),
#xml.value('(/SimpleStrategy/PrimaryTeams)[1]', 'int') as PrimaryTeams,
#xml.value('(/SimpleStrategy/SecondaryTeams)[1]', 'int') as SecondaryTeams,
#xml.value('(/SimpleStrategy/OverflowTeams)[1]', 'int') as OverflowTeams
But all I get is the TeamID's concatenated together.
,PrimaryTeams,SecondaryTeams,OverflowTeams
Default,31,0,0
Any ideas?
Thanks
Matt
Your XML shows two team IDs in <PrimaryTeams>, while both other team nodes are empty... You did not tell us anything about the expected counts in there. However, the following approach will return a kind of entity-value-pairs with all IDs for all Teams. Hope this is what you need:
;WITH XMLNAMESPACES ('http://www.w3.org/2001/XMLSchema-instance' as i, 'http://schemas.microsoft.com/2003/10/Serialization/Arrays' as d2p1,
DEFAULT 'http://schemas.datacontract.org/2004/07/Synthesys.Switch.ACD')
SELECT 'Name' AS Caption
,1 AS RowInx
,#xml.value('(/SimpleStrategy/Name)[1]', 'varchar(255)') AS Content
UNION ALL
SELECT 'Primary Team'
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
,t.value('.','varchar(255)')
FROM #xml.nodes('/SimpleStrategy/PrimaryTeams/d2p1:int') A(t)
UNION ALL
SELECT 'Secondary Team'
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
,t.value('.','varchar(255)')
FROM #xml.nodes('/SimpleStrategy/SecondaryTeams/d2p1:int') A(t)
UNION ALL
SELECT 'Overflow-Team'
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
,t.value('.','varchar(255)')
FROM #xml.nodes('/SimpleStrategy/OverflowTeams/d2p1:int') A(t);

FORXML SQL Group By Element

I am trying to group some elements together under one node. This is my current SQL;
declare #xml xml
set #xml = (
select (
select
'DERIVED' '#type',
m.NuixDerivedFieldName '#name', (
SELECT
NuixFieldType as 'metadata/#type',
NuixFieldName as 'metadata/#name'
from eddsdbo.MetadataMapping m1
where m1.NuixDerivedFieldName = m.NuixDerivedFieldName
for xml path ('first-non-blank'), type
)
from (select distinct NuixDerivedFieldName from eddsdbo.MetadataMapping) m
for xml path ('metadata'))
)
;WITH XMLNAMESPACES(DEFAULT 'http://nuix.com/fbi/metadata-profile')
select #xml for XML PATH ('metadata-list'), ROOT ('metadata-profile')
Which gives me the following output;
<metadata-profile xmlns="http://nuix.com/fbi/metadata-profile">
<metadata-list>
<metadata type="DERIVED" name="Barcode" xmlns="">
<first-non-blank>
<metadata type="CUSTOM" name="Barcode" />
</first-non-blank>
<first-non-blank>
<metadata type="EVIDENCE" name="Barcode" />
</first-non-blank>
</metadata>
I want to group together elements together which have the same 'name' attribute of the metadata element under the <first-non-blank> element.
The desired output should be;
<metadata-profile xmlns="http://nuix.com/fbi/metadata-profile">
<metadata-list>
<metadata type="DERIVED" name="Barcode" xmlns="">
<first-non-blank>
<metadata type="CUSTOM" name="Barcode" />
<metadata type="EVIDENCE" name="Barcode" />
</first-non-blank>
</metadata>
...
My database looks something like this;
NuixFieldName NuixFieldType NuixDerivedFieldName
------------------------------ ------------------------------ ------------------------------
_EmailEntryID PROPERTY EmailEntryID
Audited Audited Audited
Author PROPERTY Author
Barcode CUSTOM Barcode
Barcode EVIDENCE Barcode
I would also like to remove the xlmns namespace identifier from the metadata elements.
Thanks in advance!
You could try this
DECLARE #SampleData AS TABLE
(
NuixFieldName varchar(20),
NuixFieldType varchar(20),
NuixDerivedFieldName varchar(20)
)
INSERT INTO #SampleData
VALUES
('_EmailEntryID','PROPERTY','EmailEntryID'),
('Audited', 'Audited ','Audited'),
('Author ', 'PROPERTY','Author '),
('Barcode', 'CUSTOM ','Barcode'),
('Barcode', 'EVIDENCE','Barcode')
DECLARE #xml XML
SET #xml = (
SELECT
-- sd.NuixDerivedFieldName AS [#name],
'DERIVED' AS [#type],
sd.NuixDerivedFieldName AS [#name],
(
SELECT
sd2.NuixFieldType as '#type',
sd2.NuixFieldName as '#name'
FROM #SampleData sd2 WHERE sd2.NuixDerivedFieldName = sd.NuixDerivedFieldName
FOR XML PATH ('metadata'),ROOT('first-non-blank'), TYPE
)
FROM (select DISTINCT sd.NuixDerivedFieldName from #SampleData sd ) sd
FOR XML PATH('metadata'), ROOT('metadata-list'),TYPE
)
;WITH XMLNAMESPACES(DEFAULT 'http://nuix.com/fbi/metadata-profile')
SELECT #xml FOR XML PATH (''),ROOT('metadata-profile')
return:
<metadata-profile xmlns="http://nuix.com/fbi/metadata-profile">
<metadata-list>
<metadata type="DERIVED" name="Audited">
<first-non-blank>
<metadata type="Audited " name="Audited" />
</first-non-blank>
</metadata>
<metadata type="DERIVED" name="Author ">
<first-non-blank>
<metadata type="PROPERTY" name="Author " />
</first-non-blank>
</metadata>
<metadata type="DERIVED" name="Barcode">
<first-non-blank>
<metadata type="CUSTOM " name="Barcode" />
<metadata type="EVIDENCE" name="Barcode" />
</first-non-blank>
</metadata>
<metadata type="DERIVED" name="EmailEntryID">
<first-non-blank>
<metadata type="PROPERTY" name="_EmailEntryID" />
</first-non-blank>
</metadata>
</metadata-list>
</metadata-profile>

Extract proper data from a sql server XML column using XQuery

I am having an issue trying to get proper data from an XML type column:
"<"ArrayOfAccountInformation xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.Balance.com/">
"<"AccountInformation>
"<"AccountNumber xmlns="https://Safouenmzah.com/">0100000000"<"/AccountNumber>
"<"OutstandingAmount xmlns="https://Safouenmzah.com/">-909.55"<"/OutstandingAmount>
"<"LastBilledAmount xmlns="https://Safouenmzah.com/" />
"<"LastPaidDate xmlns="https://Safouenmzah.com/" />
"<"Severance xmlns="https://Safouenmzah.com/" />
"<"PaymentAmount xmlns="https://Safouenmzah.com/" />
"<"DistributedAmount xmlns="https://Safouenmzah.com/">$"<"/DistributedAmount>
"<"AccountInfo xmlns="https://Safouenmzah.com/">Safouen Mzah - Residential"<"/AccountInfo>
"<"/AccountInformation>
"<"/ArrayOfAccountInformation>
I am using this sql code:
;WITH XMLNAMESPACES ('http://www.Balance.com/' AS ns)
SELECT xmlResult.value('(/ns:ArrayOfAccountInformation)[1]','varchar(8000)') AS AcctInfo
FROM [dbo].[BalanceEnquiry_Transactions_Tracker]
WHERE BanlanceEnquiry_Transc_ID = 4
GO
This the result I am receiving always:
0100000000-909.55AEDSafouen Mzah - Residential
This is the expected result:
0100000000
Can some one help on this please?
Finally I figured it out.
declare #XML XML;
set #XML = '
"<"ArrayOfAccountInformation xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.Balance.com/">
"<"AccountInformation>
"<"AccountNumber xmlns="https://Safouenmzah.com/">0100000000"<"/AccountNumber>
"<"OutstandingAmount xmlns="https://Safouenmzah.com/">-909.55"<"/OutstandingAmount>
"<"LastBilledAmount xmlns="https://Safouenmzah.com/" />
"<"LastPaidDate xmlns="https://Safouenmzah.com/" />
"<"Severance xmlns="https://Safouenmzah.com/" />
"<"PaymentAmount xmlns="https://Safouenmzah.com/" />
"<"DistributedAmount xmlns="https://Safouenmzah.com/">$"<"/DistributedAmount>
"<"AccountInfo xmlns="https://Safouenmzah.com/">Safouen Mzah - Residential" <"/AccountInfo>
"<"/AccountInformation>
"<"AccountInformation>
"<"AccountNumber xmlns="https://Safouenmzah.com/">0200000000"<"/AccountNumber>
"<"OutstandingAmount xmlns="https://Safouenmzah.com/">-908.55"<"/OutstandingAmount>
"<"LastBilledAmount xmlns="https://Safouenmzah.com/" />
"<"LastPaidDate xmlns="https://Safouenmzah.com/" />
"<"Severance xmlns="https://Safouenmzah.com/" />
"<"PaymentAmount xmlns="https://Safouenmzah.com/" />
"<"DistributedAmount xmlns="https://Safouenmzah.com/">$"<"/DistributedAmount>
"<"AccountInfo xmlns="https://Safouenmzah.com/">Safouen Mzah - Expat"<"/AccountInfo>
"<"/AccountInformation>
"<"/ArrayOfAccountInformation>
'
;WITH XMLNAMESPACES ('http://www.Balance.com/' AS ns)
-- To get the outstanding amount of the first Account from the returned array
SELECT #XML.value('(/*[1]/*[1]/*[2])', 'varchar(200)') As OutstandingAmount1
-- To get the outstanding amount of the second Account from the returned array
SELECT #XML.value('(/*[1]/*[2]/*[2])', 'varchar(200)') As OutstandingAmount2
OutstandingAmount1
-909.55
OutstandingAmount2
-908.55
You can use nodes() to shred the XML and get the values in one resultset.
with xmlnamespaces('https://Safouenmzah.com/' as ns,
default 'http://www.Balance.com/')
select T.X.value('(ns:OutstandingAmount/text())[1]', 'varchar(200)')
from #XML.nodes('/ArrayOfAccountInformation/AccountInformation') as T(X)
SQL Fiddle

SQL Server XML Date Import

Having trouble importing an xml date feild into sql server, the other feilds are fine. I have tried numerous way's but it always returns as null. Any help please
2014-02-18T12:15:21.357 is the issue
The XML is
<?xml version="1.0" encoding="utf-8"?>
<MISRoot xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/IGUK.Evolution.FieldToolLite.Lib.MIS">
<Claims>
<Claim>
<Amalgamation>
<ChannelSolutions />
<Name i:nil="true" />
</Amalgamation>
<Appointments>
<Appointment>
<Access />
<AccessGranted>true</AccessGranted>
<AppointmentId>320</AppointmentId>
<EnterTime>2014-02-18T12:15:21.357</EnterTime>
<LeaveTime i:nil="true" />
<Name i:nil="true" />
</Appointment>
</Appointments>
<CustomProducts />
<Id>1220</Id>
<Payments />
<Tasks />
</Claim>
</Claims>
</MISRoot>
THE SQL is
CREATE TABLE [dbo].[xmlImportAppointments](
[ClaimId] [int] not null,
[AppointmentAUTO] [int] not NULL,
[AppointmentId] [int] not NULL,
[EnterTime] [datetime] NULL,
[LeaveTime] [datetime] NULL,
[AccessGranted] [nchar](20) NULL,
) ON [PRIMARY]
GO
WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/IGUK.Evolution.FieldToolLite.Lib.MIS')
INSERT INTO xmlImportAppointments
(ClaimId, AppointmentAUTO, AppointmentId, EnterTime, LeaveTime, AccessGranted)
SELECT
ClaimId = xmldata.value('(Claim/Id)[1]', 'int'),
AppointmentAUTO = xmldata.value('(Claim/Appointments/Appointment/AppointmentId)[1]', 'int'),
AppointmentId = xmldata.value('(Claim/Appointments/Appointment/AppointmentId)[1]', 'int'),
EnterTime = xmldata.value('(Claims/Appointment/Appointments/EnterTime)[1]', 'datetime'),
LeaveTime = xmldata.value('(Claims/Appointment/Appointments/EnterTime)[1]', 'datetime'),
AccessGranted = xmldata.value('(Claim/Appointments/Appointment/AccessGranted)[1]', 'NCHAR(20)')
FROM
(SELECT CAST(x AS XML)
FROM OPENROWSET(BULK '\\XMLTest\increment.xml',
SINGLE_BLOB) AS T(x)) AS T(x)
CROSS APPLY
x.nodes('/MISRoot/Claims') AS X(xmldata);
SELECT * FROM xmlImportAppointments
You had a problem with your XQuery I had copied your File into a XML variable and was able to retrieve using the following query.
DECLARE #MyXMLVariable XML =
'<?xml version="1.0" encoding="utf-8"?>
<MISRoot xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/IGUK.Evolution.FieldToolLite.Lib.MIS">
<Claims>
<Claim>
<Amalgamation>
<ChannelSolutions />
<Name i:nil="true" />
</Amalgamation>
<Appointments>
<Appointment>
<Access />
<AccessGranted>true</AccessGranted>
<AppointmentId>320</AppointmentId>
<EnterTime>2014-02-18T12:15:21.357</EnterTime>
<LeaveTime i:nil="true" />
<Name i:nil="true" />
</Appointment>
</Appointments>
<CustomProducts />
<Id>1220</Id>
<Payments />
<Tasks />
</Claim>
</Claims>
</MISRoot>';
WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/IGUK.Evolution.FieldToolLite.Lib.MIS')
SELECT #MyXMLVariable.value('(MISRoot/Claims/Claim/Appointments/Appointment/EnterTime)[1]','DATETIME')
You did not specify the full correct path to EnterTime
'(MISRoot/Claims/Claim/Appointments/Appointment/EnterTime)[1]' --Correct
'(Claims/Appointment/Appointments/EnterTime)[1]' --Yours
Appointment is child of Appointments not the other way around and Claim is a child of Claims best way to do this is to look at Open tags and closed tags