How to update empty XML node in MSSQL - sql-server

I want to update empty XML variable in MSSQL
i try every solutions like replace, outer apply , modify but nothing working
please help me find a solutions
<ArrayOfField xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Field>
<FieldType>1</FieldType>
<DataType>1</DataType>
<Label>department</Label>
<Name>department</Name>
<Description />
<Min />
<Max />
<DefaultValue />
<Required>0</Required>
<SelectItems />
<Formula />
<DataSourceUID xsi:nil="true" />
<TrueText />
<FalseText />
<UnconfirmtyRule xsi:nil="true" />
<UnconfirmtyRequired xsi:nil="true" />
<UnconfirmityFormUID xsi:nil="true" />
<ConfirmationStatus xsi:nil="true" />
<ConfirmationUserBasedType xsi:nil="true" />
<ConfirmationRightUsers />
<Newline>false</Newline>
<ColumnWith>12</ColumnWith>
<Offset>0</Offset>
</Field>
<Field>
<FieldType>1</FieldType>
<DataType>4</DataType>
<Label>Test</Label>
<Name>test</Name>
<Description />
<Min />
<Max />
<DefaultValue />
<Required>0</Required>
<SelectItems />
<Formula />
<TrueText />
<FalseText />
<UnconfirmtyRule xsi:nil="true" />
<UnconfirmtyRequired xsi:nil="true" />
<UnconfirmityFormUID xsi:nil="true" />
<ConfirmationStatus xsi:nil="true" />
<ConfirmationUserBasedType xsi:nil="true" />
<ConfirmationRightUsers />
<Newline>false</Newline>
<ColumnWith>12</ColumnWith>
<Offset>0</Offset>
</Field>
</ArrayOfField>
I want update DefaultValue if DataType = 1
New DefaultValue like <DefaultValue>TODAY()<DefaultValue/>
I try this code but not update anything what is my mistake?
DECLARE #SearchType NVARCHAR(100)=N'1';
DECLARE #ReplaceWith NVARCHAR(100)=N'TODAY()';
UPDATE FormSchema
SET Fields.modify('replace value of
(/ArrayOfField
/Field[DataType=sql:variable("#SearchType")]
/DefaultValue/text())[1]
with sql:variable("#ReplaceWith")')
WHERE Fields.exist('/ArrayOfField
/Field[DataType=sql:variable("#SearchType")]')=1;

You need to use different XML modify operations depending on whether the target element is empty or not (i.e.: it contains no text as opposed to being xsi:nil="true"). For example...
--
-- Setup data...
--
create table dbo.FormSchema (
Fields xml
);
insert dbo.FormSchema (Fields) values
(N'<ArrayOfField>
<Field>
<DataType>1</DataType>
<DefaultValue>Hello, world!</DefaultValue>
</Field>
<Field>
<DataType>2</DataType>
<DefaultValue />
</Field>
</ArrayOfField>'),
(N'<ArrayOfField>
<Field>
<DataType>1</DataType>
<DefaultValue />
</Field>
<Field>
<DataType>3</DataType>
<DefaultValue />
</Field>
</ArrayOfField>');
--
-- Perform updates...
--
DECLARE
#SearchType NVARCHAR(100) = N'1',
#ReplaceWith NVARCHAR(100) = N'TODAY()';
UPDATE dbo.FormSchema
SET Fields.modify('
replace value of (/ArrayOfField/Field[DataType=sql:variable("#SearchType")]/DefaultValue/text())[1]
with sql:variable("#ReplaceWith")
')
WHERE Fields.exist('(/ArrayOfField/Field[DataType=sql:variable("#SearchType")]/DefaultValue/text())[1]')=1;
UPDATE dbo.FormSchema
SET Fields.modify('
insert text{sql:variable("#ReplaceWith")}
into (/ArrayOfField/Field[DataType=sql:variable("#SearchType")]/DefaultValue)[1]
')
WHERE Fields.exist('(/ArrayOfField/Field[DataType=sql:variable("#SearchType")]/DefaultValue)[1]')=1
AND Fields.exist('(/ArrayOfField/Field[DataType=sql:variable("#SearchType")]/DefaultValue/text())[1]')=0;
--
-- Check results...
--
SELECT * FROM dbo.FormSchema;
Which yields the results:
Fields
<ArrayOfField><Field><DataType>1</DataType><DefaultValue>TODAY()</DefaultValue></Field><Field><DataType>2</DataType><DefaultValue /></Field></ArrayOfField>
<ArrayOfField><Field><DataType>1</DataType><DefaultValue>TODAY()</DefaultValue></Field><Field><DataType>3</DataType><DefaultValue /></Field></ArrayOfField>

Related

SQL Server xml query doesn't return expected result

I have a column in my database FlowDetailParameter with XML Type .My table has one column FlowDetailParameter and 3 rows with these data :
row 1
<ArrayOfFlowDetailParameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FlowDetailParameters>
<DepartmentId>7</DepartmentId>
<UserId>6</UserId>
<Username>4</Username>
<FullName>کارشناس معاینه فنی</FullName>
<ConfirmDateTime>2018-11-01T10:45:29.7371421+03:30</ConfirmDateTime>
<Comment>اولین IP تاییدی</Comment>
<Status>Accept</Status>
</FlowDetailParameters>
<FlowDetailParameters>
<DepartmentId>3</DepartmentId>
<UserId xsi:nil="true" />
<Username />
<FullName />
<ConfirmDateTime xsi:nil="true" />
<Comment />
<Status>Pending</Status>
<AttachmentId />
</FlowDetailParameters>
</ArrayOfFlowDetailParameters>
row 2
<ArrayOfFlowDetailParameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FlowDetailParameters>
<DepartmentId>7</DepartmentId>
<UserId>6</UserId>
<Username>4</Username>
<FullName>کارشناس معاینه فنی</FullName>
<ConfirmDateTime>2018-11-01T10:45:40.437481+03:30</ConfirmDateTime>
<Comment>دومین IP تاییدی</Comment>
<Status>Accept</Status>
</FlowDetailParameters>
<FlowDetailParameters>
<DepartmentId>3</DepartmentId>
<UserId xsi:nil="true" />
<Username />
<FullName />
<ConfirmDateTime xsi:nil="true" />
<Comment />
<Status>Pending</Status>
<AttachmentId />
</FlowDetailParameters>
</ArrayOfFlowDetailParameters>
row 3
<ArrayOfFlowDetailParameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FlowDetailParameters>
<DepartmentId>7</DepartmentId>
<UserId xsi:nil="true" />
<Username />
<FullName />
<ConfirmDateTime xsi:nil="true" />
<Comment />
<Status>Pending</Status>
<AttachmentId />
</FlowDetailParameters>
<FlowDetailParameters>
<DepartmentId>3</DepartmentId>
<UserId xsi:nil="true" />
<Username />
<FullName />
<ConfirmDateTime xsi:nil="true" />
<Comment />
<Status />
<AttachmentId />
</FlowDetailParameters>
</ArrayOfFlowDetailParameters>
I want to find the departmentId=3 and status=Pending ,so the expected result should return 2 rows .So here is my query :
select Requests.* from Requests
where
((SELECT count(*)
FROM Requests t
CROSS APPLY t.FlowDetailParameter.nodes ('/ArrayOfFlowDetailParameters/FlowDetailParameters') x(v)
where x.v.value('(DepartmentId/text())[1]', 'bigint')=3 and x.v.value('(Status/text())[1]', 'varchar(50)') = 'Pending') >0)
But my query returns all rows (3 rows) why ?
First to answer your question "why?":
Your sub-query is not a correlated sub-query. There is no connection to the current row from the outer SELECT. So - assuming there is at least 1 row fulfilling your condition - this will always provide a count>0.
Although your approach can be corrected, I'd suggest to use the XML-method .exist() and provide the filter as XPath/XQuery:
SELECT *
FROM Requests r
WHERE r.FlowDetailParameter.exist(N'/ArrayOfFlowDetailParameters
/FlowDetailParameters[(DepartmentId/text())[1]=3
and (Status/text())[1]="Pending"]')=1;
This will check for the existance of any <FlowDetailParameters> for the given condition.
If you want to introduce the filter dynamically, you can use sql:variable() or sql:column() instead of 3 and "Pending"
DECLARE #depId INT=3;
DECLARE #status VARCHAR(100)='Pending';
SELECT *
FROM Requests r
WHERE r.FlowDetailParameter.exist(N'/ArrayOfFlowDetailParameters
/FlowDetailParameters[(DepartmentId/text())[1]=sql:variable("#depId")
and (Status/text())[1]=sql:variable("#status")]')=1

SQL Server xml query can't return expected result

I have this xml data in my table as you can see :
<ArrayOfFlowDetailParameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FlowDetailParameters>
<DepartmentId>23</DepartmentId>
<UserId xsi:nil="true" />
<Username />
<FullName />
<ConfirmDateTime xsi:nil="true" />
<Comment />
<Status>Pending</Status>
<AttachmentId />
</FlowDetailParameters>
<FlowDetailParameters>
<DepartmentId>22</DepartmentId>
<UserId xsi:nil="true" />
<Username />
<FullName />
<ConfirmDateTime xsi:nil="true" />
<Comment />
<Status>Pending</Status>
<AttachmentId />
</FlowDetailParameters>
<FlowDetailParameters>
<DepartmentId>7</DepartmentId>
<UserId xsi:nil="true" />
<Username />
<FullName />
<ConfirmDateTime xsi:nil="true" />
<Comment />
<Status>Pending</Status>
<AttachmentId />
</FlowDetailParameters>
<FlowDetailParameters>
<DepartmentId>18</DepartmentId>
<UserId xsi:nil="true" />
<Username />
<FullName />
<ConfirmDateTime xsi:nil="true" />
<Comment />
<Status>Pending</Status>
<AttachmentId />
</FlowDetailParameters>
</ArrayOfFlowDetailParameters>
when i want to find the departmentid with value=22 my query returns 0 result but when i search value=23 it returns 1 result i think it is because of [1].
declare #departmentId nvarchar(max)
set #departmentId=22
select Requests.* from Requests
where
and (FlowDetailParameter.value('(/ArrayOfFlowDetailParameters/FlowDetailParameters/DepartmentId/text())[1]','bigint') = #departmentId )
It sounds like you're trying to query a list of requests where the FlowDetailParameter column's XML contains a record where the DepartmentId matches your #departmentId variable, right?
The [1] in your query specifies to only check the first occurrence of DepartmentId in each row's FlowDetailParameter XML. You won't get a match unless the first DepartmentId in the XML matches your parameter.
Instead, you can use the following query to find all requests that have a FlowDetailParameter matching the #departmentid variable using the nodes() method.
SELECT r.*
FROM #Requests r
WHERE EXISTS (SELECT *
FROM r.FlowDetailParameter.nodes('/ArrayOfFlowDetailParameters/FlowDetailParameters/DepartmentId') as Parms(DepartmentId)
WHERE DepartmentId.value('.', 'bigint') = #departmentid)

Updating multiple XML columns using single update in SQL Server

I would like to update a table_A with new values for (AcresDist1, txtAcresDist1, txtAcresDist1Total) XML columns from a second table_B.
The column P_XML is of XML type. I know how to update a single column at once, but I would like to know how to update multiple columns in the XML using a single update statement. Thanks
SQL code:
UPDATE S
SET
P_XML.modify( N'replace value of (/FormValue/f1152_F1/Field[(id/text())[1]="AcresDist1"]/value/text())[1] with sql:column(''T.AcresDist1'')' )
, P_XML.modify( N'replace value of (/FormValue/f1152_F1/Field[(id/text())[1]="txtAcresDist1"]/value/text())[1] with sql:column(''T.txtAcresDist'')' )
, P_XML.modify( N'replace value of (/FormValue/f1152_F1/Field[(id/text())[1]="txtAcresDist1Total"]/value/text())[1] with sql:column(''T.txtAcresDist1Total'')' )
FROM
Table_A AS S
INNER JOIN
Table_B AS T ON s.P_NO = t.P_Number
AND s.FAC_RID = t.Fac_RID;
Here is the sample xml as requested. Thank you.
<FormValue>
<f1152>
<field>
<id>f1152_MainForm</id>
<value />
<tag />
<visible>true</visible>
<history>|09/28/2017 10:50:26 AM||</history>
<description />
<comment />
</field>
<field>
<id>txt_rdoCoverage</id>
<value>Development</value>
<tag />
<visible>false</visible>
<history>|09/28/2017 10:50:26 AM||</history>
<description />
<comment />
</field>
</f1152>
<f1152_F1>
<field>
<id>txtAcresDist1</id>
<value>1.2</value>
<tag />
<visible>false</visible>
<history>|09/28/2017 3:08:14 AM||</history>
<description />
<comment />
</field>
<field>
<id>txtAcresDist1Total</id>
<value>200</value>
<tag />
<visible>false</visible>
<history>|09/28/2017 3:08:14 AM||</history>
<description />
<comment />
</field>
</f1152_F1>

Select from xml file stored procedure running infinitely returning thousands of duplicate records

I have this stored procedure which returns a lot of duplicate records due to wrong cross apply i suppose. Take a look at the screenshot of result set. Case number 000110-54-3 is only hexane but I get other chemical names related to other case numbers also listed for the same case number. Thus, the query runs forever for other cross\outer apply. Any help appreciated.
XML file catalog item (it's kinda large one)
<ArrayOfCatalogItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CatalogItem Version="1">
<Container xmlns="http://3ecompany.com/webservices/catalogitemxml">
<ContainerSize>
<Value>10.500000000</Value>
<Units>OunceUS</Units>
</ContainerSize>
<ContainerType>Unknown</ContainerType>
<MarkedForRetail xsi:nil="true" />
</Container>
<Documents CultureCode="en" Elink="https://3eonline.com/ImageServer/ImageViewer.aspx?id=3Q%2ffAR8ne%2fvPh6syVnSymkS%2bBDo8OjmbVocxRCMEgeENagNJzc81tOXY0yL87aEPfwnzvlaVmM1mbrA2r7BYXNzA43I%2baZTLYlibHjHcCDI%3d" Format="Msds" DocumentType="Sds" Country="USA" DocumentId="SDS8672822" RevisionDate="2015-05-18T00:00:00" xmlns="http://3ecompany.com/webservices/catalogitemxml" />
<IsHazardous xmlns="http://3ecompany.com/webservices/catalogitemxml">true</IsHazardous>
<ManufacturerName xmlns="http://3ecompany.com/webservices/catalogitemxml">Permatex Inc.</ManufacturerName>
<Msds xmlns="http://3ecompany.com/webservices/catalogitemxml">
<Elink>https://3eonline.com/ImageServer/ImageViewer.aspx?id=3Q%2ffAR8ne%2fvPh6syVnSymqIuIP5CInA01ZbaRQ9r18GfjipRC2KgVeHKeJd2rplH4f%2b5u6E0coedMiZYmt%2fs1A%3d%3d</Elink>
<FireCodeClassification>
<Asphyxiant>false</Asphyxiant>
<WaterReactive xsi:nil="true" />
<Hmis Chronic="true" Fire="4" Health="2" Reactivity="0" Special="X" />
<Nfpa Fire="4" Health="1" Reactivity="0" Special="" />
<Sara>
<Delayed>true</Delayed>
<Fire>true</Fire>
<Immediate>true</Immediate>
<Pressure>true</Pressure>
<Reactivity>false</Reactivity>
</Sara>
<DerivedPhysicalState>Aerosol</DerivedPhysicalState>
</FireCodeClassification>
<Ingredients>
<ChemicalName>Hexane</ChemicalName>
<Cas>000110-54-3</Cas>
<Percent>30.000000</Percent>
<PercentMin>10.000000</PercentMin>
<PercentOperator>LessThanOrEqualTo</PercentOperator>
<PercentMinOperator>GreaterThanOrEqualTo</PercentMinOperator>
<PercentUnits>ByWeight</PercentUnits>
<PercentModifier xsi:nil="true" />
<MinPercent>10.000000</MinPercent>
<MaxPercent>30.000000</MaxPercent>
<Sara313Details>
<ChemicalKey>110543</ChemicalKey>
<Deminimus />
<IsPBT>false</IsPBT>
<IsSara313Toxic>true</IsSara313Toxic>
<ReportingThreshold>
<Value>25000</Value>
<Units>Pound</Units>
</ReportingThreshold>
<SaraChemName>N-HEXANE</SaraChemName>
</Sara313Details>
<Sara302Details>
<ChemicalKey>110543</ChemicalKey>
<IsSara302Ehs>false</IsSara302Ehs>
</Sara302Details>
<OshaPelDetails>
<ChemicalKey>110543</ChemicalKey>
<OshaPelChemName>N-HEXANE</OshaPelChemName>
<Type>Z1</Type>
<Twa>500</Twa>
<TwaUnits>unknown unit type</TwaUnits>
<TwaInMg>1800</TwaInMg>
<Stel xsi:nil="true" />
<CeilInPpm xsi:nil="true" />
<CeilInMg xsi:nil="true" />
<PeakInPpm xsi:nil="true" />
<PeakInMg xsi:nil="true" />
</OshaPelDetails>
<AcgihTlvDetails>
<ChemicalKey>110543</ChemicalKey>
<AcgihTlvChemName>N-HEXANE</AcgihTlvChemName>
<SkinDesignation>true</SkinDesignation>
<Sensitizer>false</Sensitizer>
<SimpleAsphyxiant>false</SimpleAsphyxiant>
<CarcinogenCategory />
<YearKnowCarcinogen />
<ExposureByAllRoutes>false</ExposureByAllRoutes>
<Twa xsi:nil="true" />
<TwaInPpm>50</TwaInPpm>
<StelInPpm xsi:nil="true" />
<StelInMg xsi:nil="true" />
<CeilInPpm xsi:nil="true" />
<CeilInMg xsi:nil="true" />
<MolecularWeight>86.18</MolecularWeight>
<TlvBasisCriticalEffect>CNS impair; peripheral neuropathy; eye irr</TlvBasisCriticalEffect>
</AcgihTlvDetails>
<AvgPercent>20.000000</AvgPercent>
</Ingredients>
<Ingredients>
<ChemicalName>2-Propanone</ChemicalName>
<Cas>000067-64-1</Cas>
<Percent>30.000000</Percent>
<PercentMin>10.000000</PercentMin>
<PercentOperator>LessThanOrEqualTo</PercentOperator>
<PercentMinOperator>GreaterThanOrEqualTo</PercentMinOperator>
<PercentUnits>ByWeight</PercentUnits>
<PercentModifier xsi:nil="true" />
<MinPercent>10.000000</MinPercent>
<MaxPercent>30.000000</MaxPercent>
<Sara313Details>
<ChemicalKey>67641</ChemicalKey>
<IsPBT>false</IsPBT>
<IsSara313Toxic>false</IsSara313Toxic>
</Sara313Details>
<Sara302Details>
<ChemicalKey>67641</ChemicalKey>
<IsSara302Ehs>false</IsSara302Ehs>
</Sara302Details>
<OshaPelDetails>
<ChemicalKey>67641</ChemicalKey>
<OshaPelChemName>ACETONE</OshaPelChemName>
<Type>Z1</Type>
<Twa>1000</Twa>
<TwaUnits>unknown unit type</TwaUnits>
<TwaInMg>2400</TwaInMg>
<Stel xsi:nil="true" />
<CeilInPpm xsi:nil="true" />
<CeilInMg xsi:nil="true" />
<PeakInPpm xsi:nil="true" />
<PeakInMg xsi:nil="true" />
</OshaPelDetails>
<AcgihTlvDetails>
<ChemicalKey>67641</ChemicalKey>
<AcgihTlvChemName>ACETONE</AcgihTlvChemName>
<SkinDesignation>false</SkinDesignation>
<Sensitizer>false</Sensitizer>
<SimpleAsphyxiant>false</SimpleAsphyxiant>
<CarcinogenCategory>A4</CarcinogenCategory>
<YearKnowCarcinogen />
<ExposureByAllRoutes>false</ExposureByAllRoutes>
<Twa xsi:nil="true" />
<TwaInPpm>250</TwaInPpm>
<StelInPpm>500</StelInPpm>
<StelInMg xsi:nil="true" />
<CeilInPpm xsi:nil="true" />
<CeilInMg xsi:nil="true" />
<MolecularWeight>58.05</MolecularWeight>
<TlvBasisCriticalEffect>URT & eye irr; CNS impair</TlvBasisCriticalEffect>
</AcgihTlvDetails>
<AvgPercent>20.000000</AvgPercent>
</Ingredients>
<MsdsId>8672822</MsdsId>
<MsdsMfgName>Permatex USA</MsdsMfgName>
<MsdsProductName>118Da All Purpose Spray Adhesive 11 oz</MsdsProductName>
<Properties>
<PhysicalState>Aerosol</PhysicalState>
<BoilingPoint>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Celsius</Units>
<Value>38.0000</Value>
</BoilingPoint>
<FlashPoint>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Celsius</Units>
<Value>-18.0000</Value>
</FlashPoint>
<MolecularWeight xsi:nil="true" />
<Ph xsi:nil="true" />
<SpecificGravity>0.7300</SpecificGravity>
<VaporDensity xsi:nil="true" />
<Uel xsi:nil="true" />
<Lel xsi:nil="true" />
<BoilingPointInCelsius>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Celsius</Units>
<Value>38</Value>
</BoilingPointInCelsius>
<FlashPointInCelsius>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Celsius</Units>
<Value>-18</Value>
</FlashPointInCelsius>
<BoilingPointInFahrenheit>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Fahrenheit</Units>
<Value>100.4</Value>
</BoilingPointInFahrenheit>
<FlashPointInFahrenheit>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Fahrenheit</Units>
<Value>-0.399999999999999</Value>
</FlashPointInFahrenheit>
</Properties>
<RevisionDate>2015-05-18T00:00:00</RevisionDate>
<MsdsRevListId>3836824</MsdsRevListId>
<SdsConfirmationDate>2015-05-18T00:00:00</SdsConfirmationDate>
<ClassificationCompleted>true</ClassificationCompleted>
<CasCompleted>true</CasCompleted>
<PropertiesCompleted>true</PropertiesCompleted>
<Locale>en</Locale>
<DocumentFormat>Msds</DocumentFormat>
<Country>USA</Country>
<MsdsLanguage>en</MsdsLanguage>
<MsdsRegion>UnitedStates</MsdsRegion>
<SdsNotRequired>false</SdsNotRequired>
<MfgContactInfo>
<MfgAddress>6875 Parkland Boulevard</MfgAddress>
<MfgCity>Solon</MfgCity>
<MfgState>Ohio</MfgState>
<MfgCountry>United States</MfgCountry>
<MfgPostalCode>44139</MfgPostalCode>
<MfgPhoneCountryCode />
<MfgPhoneAreaCode>440</MfgPhoneAreaCode>
<MfgPhoneNumber>914-3571</MfgPhoneNumber>
<MfgPhoneExtension />
<MfgFaxCountryCode />
<MfgFaxAreaCode>440</MfgFaxAreaCode>
<MfgFaxNumber>914-3500</MfgFaxNumber>
<MfgFaxExtension />
<MfgEmail>denise.boyd#permatex.com</MfgEmail>
<MfgWebUrl>http://www.permatex.com</MfgWebUrl>
</MfgContactInfo>
<GhsClassification>
<SignalWord>None</SignalWord>
<SignalWordText>Danger</SignalWordText>
<Pictograms>
<Code>GHS02</Code>
</Pictograms>
<Pictograms>
<Code>GHS07</Code>
</Pictograms>
<Pictograms>
<Code>GHS08</Code>
</Pictograms>
<HazardClasses>
<HazardClassText>Flammable aerosol.</HazardClassText>
<CategoryText>Category 1</CategoryText>
<HazardClassPhraseTextID>92876</HazardClassPhraseTextID>
<CategoryPhraseTextID>93598</CategoryPhraseTextID>
<InternalHazardClassPhraseID>4059</InternalHazardClassPhraseID>
<InternalHazardClassPhraseLangCode>en</InternalHazardClassPhraseLangCode>
<InternalCategoryPhraseID>4082</InternalCategoryPhraseID>
<InternalCategoryPhraseLangCode>EN</InternalCategoryPhraseLangCode>
</HazardClasses>
<PCodes>
<SequenceNumber>401</SequenceNumber>
<Pcode>P405</Pcode>
<PcodeText>Store locked up.</PcodeText>
<PcodeSubTypeText>Storage</PcodeSubTypeText>
<PcodePhraseTextID>91288</PcodePhraseTextID>
<InternalPcodePhraseID>4009</InternalPcodePhraseID>
<InternalPcodePhraseLangCode>EN</InternalPcodePhraseLangCode>
</PCodes>
<HCodes>
<SequenceNumber>1</SequenceNumber>
<Hcode>H315</Hcode>
<HcodeText>Causes skin irritation.</HcodeText>
<HcodeSubTypeText>HealthHazard</HcodeSubTypeText>
<HcodePhraseTextID>91544</HcodePhraseTextID>
<InternalHcodePhraseID>4017</InternalHcodePhraseID>
<InternalHcodePhraseLangCode>EN</InternalHcodePhraseLangCode>
<SignalWordPhraseTextID>236050</SignalWordPhraseTextID>
<InternalSignalWordPhraseId>22738</InternalSignalWordPhraseId>
<InternalSignalWordPhraseLangCode>EN</InternalSignalWordPhraseLangCode>
</GhsClassification>
<TransportationClassificationCompleted xsi:nil="true" />
<WasteCompleted xsi:nil="true" />
<ExtendedSds>false</ExtendedSds>
<TransportationExceptionClassificationCompleted xsi:nil="true" />
<BestAvailable>false</BestAvailable>
</Msds>
<ProductIdentifiers xmlns="http://3ecompany.com/webservices/catalogitemxml">
<Identifier>M007628</Identifier>
<Source>CPN</Source>
<FirstExportDate xsi:nil="true" />
<LastExportDate xsi:nil="true" />
<FlaggedForResend xsi:nil="true" />
</ProductIdentifiers>
<ProductName xmlns="http://3ecompany.com/webservices/catalogitemxml">118DA All Purpose Spray Adhesive - 82019 (10.5 oz aerosol)</ProductName>
<ProductUid xmlns="http://3ecompany.com/webservices/catalogitemxml">2501f87679eb40c5bff24e9e84170ff1</ProductUid>
<Locations xmlns="http://3ecompany.com/webservices/catalogitemxml">
<LocationUid>e504e4605e9c4da6a6243d617b45593f</LocationUid>
<Name>LUS Philadelphia (New Inventory)</Name>
<ChemicalApprovalStatus>None</ChemicalApprovalStatus>
<Quantity xsi:nil="true" />
<LocationPath>American Airlines > PHL > LUS Philadelphia (New Inventory)</LocationPath>
<ChemicalApprovalConditionalNotes />
<Notes />
<ActivatedBy>tehrman</ActivatedBy>
<ActivatedOn>2016-06-06T11:04:47.193</ActivatedOn>
</Locations>
<EeeProductId xmlns="http://3ecompany.com/webservices/catalogitemxml">3319854</EeeProductId>
<EeeCpcId xmlns="http://3ecompany.com/webservices/catalogitemxml">15071137</EeeCpcId>
<ConverterData xmlns="http://3ecompany.com/webservices/catalogitemxml" />
<CreatedBy xmlns="http://3ecompany.com/webservices/catalogitemxml">ondata</CreatedBy>
<CreatedDate xmlns="http://3ecompany.com/webservices/catalogitemxml">4/25/2016</CreatedDate>
<IsDeactivated xmlns="http://3ecompany.com/webservices/catalogitemxml">false</IsDeactivated>
<DeactivatedDate xsi:nil="true" xmlns="http://3ecompany.com/webservices/catalogitemxml" />
</CatalogItem>
</ArrayOfCatalogItem>
The stored procedure which reads from this xml returns a lot of duplicates
This is a rough draft stored procedure, I know I can shorten it further but I'll do it once I figure out everything else.
BEGIN
DECLARE #XmlTable TABLE (XMLDATA XML)
INSERT INTO #XmlTable(XMLData)
SELECT CONVERT(XML, BulkColumn) AS BulkColumn
FROM OPENROWSET(BULK 'C:\AA.Sample.File.LUS.Pilly-oneCI.xml', SINGLE_BLOB) AS x;
;WITH XMLNAMESPACES ('http://3ecompany.com/webservices/catalogitemxml' as CI)
SELECT
--CIVersion = CI.value('#Version', 'int'),
Identifier = PID.value('(.)[1]', 'varchar(9)'),
Product_Name = MSDSPN.value('(.)[1]','varchar(100)'),
Revision_Date = RevDt.value('(.)[1]', 'Datetime'),
Review_Date = RevwDt.value('(.)[1]', 'Datetime'),
Density = Dy.value('(.)[1]', 'float'),
Specific_Gravity = SG.value('(.)[1]', 'float'),
Manufacturer_Name = MN.value('(.)[1]', 'varchar(80)'),
Manufacturer_Address = Mad.value('(.)[1]', 'varchar(80)'),
Manufacturer_City = MCY.value('(.)[1]', 'varchar(40)'),
Manufacturer_State = MST.value('(.)[1]', 'varchar(20)'),
Manufacturer_Postal_Code = MPC.value('(.)[1]', 'varchar(20)'),
CAS_Number = CAS.value('(.)[1]', 'varchar(20)'),
Chemical_Name = CN.value('(.)[1]', 'varchar(100)'),
Weight_Percent = PC.value('(.)[1]', 'varchar(50)'),
Min_Weight_Percent = MNPC.value('(.)[1]', 'float'),
Max_Weight_Percent = MXPC.value('(.)[1]', 'float'),
Container_Size = CSV.value('(.)[1]', 'float'),
Container_Unit = CSU.value('(.)[1]', 'varchar(30)'),
SARA_Fire = SF.value('(.)[1]', 'bit'),
SARA_Release = SR.value('(.)[1]', 'bit'),
SARA_Reactivity = SRY.value('(.)[1]', 'bit'),
SARA_Acute = SRA.value('(.)[1]', 'bit'),
SARA_Chronic = SRC.value('(.)[1]', 'bit'),
EHS = SDV.value('(.)[1]', 'bit'),
-- TPQ_Pounds = if(SRTX.value('(.)[1]','bit')) return SDV.value('(.)[1]', 'int')) else (return 0),
Solid = PS.exist('(.)[contains(.,"Solid")]'),
Liquid = PS.exist('(.)[contains(.,"Liquid")]'),
Gas = PS.exist('(.)[contains(.,"Gas")]'),
Container_Code = CTP.value('(.)[1]', 'varchar(10)')
FROM
#XmlTable
Outer APPLY
XMLData.nodes('/ArrayOfCatalogItem/CatalogItem') AS XT(CI)
OUTER APPLY
CI.nodes('CI:ProductIdentifiers/CI:Identifier') AS XT2(PID)
OUTER APPLY
CI.nodes('CI:Msds/CI:MsdsProductName') AS XT3(MSDSPN)
OUTER APPLY
CI.nodes('CI:Msds/CI:RevisionDate') AS XT4(RevDt)
OUTER APPLY
CI.nodes('CI:Msds/CI:SdsConfirmationDate') AS XT5(RevwDt)
OUTER APPLY
CI.nodes('CI:Msds/CI:Properties/CI:Density/CI:Value') AS XT6(Dy)
OUTER APPLY
CI.nodes('CI:Msds/CI:Properties/CI:SpecificGravity') AS XT7(SG)
OUTER APPLY
CI.nodes('CI:ManufacturerName') AS XT13(Mn)
OUTER APPLY
CI.nodes('CI:Msds/CI:MfgContactInfo/CI:MfgAddress') AS XT14(Mad)
OUTER APPLY
CI.nodes('CI:Msds/CI:MfgContactInfo/CI:MfgCity') AS XT15(MCY)
OUTER APPLY
CI.nodes('CI:Msds/CI:MfgContactInfo/CI:MfgState') AS XT16(MST)
OUTER APPLY
CI.nodes('CI:Msds/CI:MfgContactInfo/CI:MfgPostalCode') AS XT17(MPC)
OUTER APPLY
CI.nodes('CI:Msds/CI:Ingredients/CI:Cas') AS XT18(CAS)
OUTER APPLY
CI.nodes('CI:Msds/CI:Ingredients/CI:ChemicalName') AS XT19(CN)
OUTER APPLY
CI.nodes('CI:Msds/CI:Ingredients/CI:Percent') AS XT20(PC)
OUTER APPLY
CI.nodes('CI:Msds/CI:Ingredients/CI:MinPercent') AS XT21(MNPC)
OUTER APPLY
CI.nodes('CI:Msds/CI:Ingredients/CI:MaxPercent') AS XT22(MXPC)
OUTER APPLY
CI.nodes('CI:Msds/CI:FireCodeClassification/CI:Sara/CI:Fire') AS XT8(SF)
OUTER APPLY
CI.nodes('CI:Container/CI:ContainerSize/CI:Value') AS XT25(CSV)
OUTER APPLY
CI.nodes('CI:Container/CI:ContainerSize/CI:Units') AS XT26(CSU)
OUTER APPLY
CI.nodes('CI:Msds/CI:FireCodeClassification/CI:Sara/CI:Pressure') AS XT9(SR)
OUTER APPLY
CI.nodes('CI:Msds/CI:FireCodeClassification/CI:Sara/CI:Reactivity') AS XT10(SRY)
OUTER APPLY
CI.nodes('CI:Msds/CI:FireCodeClassification/CI:Sara/CI:Immediate') AS XT11(SRA)
OUTER APPLY
CI.nodes('CI:Msds/CI:FireCodeClassification/CI:Sara/CI:Delayed') AS XT12(SRC)
CROSS APPLY
CI.nodes('CI:Msds/CI:Ingredients/CI:Sara313Details/CI:IsSara313Toxic') AS XT23(SRTX)
OUTER APPLY
CI.nodes('CI:Msds/CI:Ingredients/CI:Sara313Details/CI:ReportingThreshold/CI:Value') AS XT24(SDV)
CROSS APPLY
CI.nodes('CI:Msds/CI:Properties/CI:PhysicalState') AS XT27(PS)
OUTER APPLY
CI.nodes('CI:Container/CI:ContainerType') AS XT28(CTP)
END
In your attempt there are far to many APPLYs. You need them in cases of nested 1:n only!
Most of your nestings are boundled but 1:1. You read these values just with a longer XPath.
Btw: There was a closing </HCodes> missing in your XML.
Your XML
DECLARE #xml XML=
'<ArrayOfCatalogItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CatalogItem Version="1">
<Container xmlns="http://3ecompany.com/webservices/catalogitemxml">
<ContainerSize>
<Value>10.500000000</Value>
<Units>OunceUS</Units>
</ContainerSize>
<ContainerType>Unknown</ContainerType>
<MarkedForRetail xsi:nil="true" />
</Container>
<Documents CultureCode="en" Elink="https://3eonline.com/ImageServer/ImageViewer.aspx?id=3Q%2ffAR8ne%2fvPh6syVnSymkS%2bBDo8OjmbVocxRCMEgeENagNJzc81tOXY0yL87aEPfwnzvlaVmM1mbrA2r7BYXNzA43I%2baZTLYlibHjHcCDI%3d" Format="Msds" DocumentType="Sds" Country="USA" DocumentId="SDS8672822" RevisionDate="2015-05-18T00:00:00" xmlns="http://3ecompany.com/webservices/catalogitemxml" />
<IsHazardous xmlns="http://3ecompany.com/webservices/catalogitemxml">true</IsHazardous>
<ManufacturerName xmlns="http://3ecompany.com/webservices/catalogitemxml">Permatex Inc.</ManufacturerName>
<Msds xmlns="http://3ecompany.com/webservices/catalogitemxml">
<Elink>https://3eonline.com/ImageServer/ImageViewer.aspx?id=3Q%2ffAR8ne%2fvPh6syVnSymqIuIP5CInA01ZbaRQ9r18GfjipRC2KgVeHKeJd2rplH4f%2b5u6E0coedMiZYmt%2fs1A%3d%3d</Elink>
<FireCodeClassification>
<Asphyxiant>false</Asphyxiant>
<WaterReactive xsi:nil="true" />
<Hmis Chronic="true" Fire="4" Health="2" Reactivity="0" Special="X" />
<Nfpa Fire="4" Health="1" Reactivity="0" Special="" />
<Sara>
<Delayed>true</Delayed>
<Fire>true</Fire>
<Immediate>true</Immediate>
<Pressure>true</Pressure>
<Reactivity>false</Reactivity>
</Sara>
<DerivedPhysicalState>Aerosol</DerivedPhysicalState>
</FireCodeClassification>
<Ingredients>
<ChemicalName>Hexane</ChemicalName>
<Cas>000110-54-3</Cas>
<Percent>30.000000</Percent>
<PercentMin>10.000000</PercentMin>
<PercentOperator>LessThanOrEqualTo</PercentOperator>
<PercentMinOperator>GreaterThanOrEqualTo</PercentMinOperator>
<PercentUnits>ByWeight</PercentUnits>
<PercentModifier xsi:nil="true" />
<MinPercent>10.000000</MinPercent>
<MaxPercent>30.000000</MaxPercent>
<Sara313Details>
<ChemicalKey>110543</ChemicalKey>
<Deminimus />
<IsPBT>false</IsPBT>
<IsSara313Toxic>true</IsSara313Toxic>
<ReportingThreshold>
<Value>25000</Value>
<Units>Pound</Units>
</ReportingThreshold>
<SaraChemName>N-HEXANE</SaraChemName>
</Sara313Details>
<Sara302Details>
<ChemicalKey>110543</ChemicalKey>
<IsSara302Ehs>false</IsSara302Ehs>
</Sara302Details>
<OshaPelDetails>
<ChemicalKey>110543</ChemicalKey>
<OshaPelChemName>N-HEXANE</OshaPelChemName>
<Type>Z1</Type>
<Twa>500</Twa>
<TwaUnits>unknown unit type</TwaUnits>
<TwaInMg>1800</TwaInMg>
<Stel xsi:nil="true" />
<CeilInPpm xsi:nil="true" />
<CeilInMg xsi:nil="true" />
<PeakInPpm xsi:nil="true" />
<PeakInMg xsi:nil="true" />
</OshaPelDetails>
<AcgihTlvDetails>
<ChemicalKey>110543</ChemicalKey>
<AcgihTlvChemName>N-HEXANE</AcgihTlvChemName>
<SkinDesignation>true</SkinDesignation>
<Sensitizer>false</Sensitizer>
<SimpleAsphyxiant>false</SimpleAsphyxiant>
<CarcinogenCategory />
<YearKnowCarcinogen />
<ExposureByAllRoutes>false</ExposureByAllRoutes>
<Twa xsi:nil="true" />
<TwaInPpm>50</TwaInPpm>
<StelInPpm xsi:nil="true" />
<StelInMg xsi:nil="true" />
<CeilInPpm xsi:nil="true" />
<CeilInMg xsi:nil="true" />
<MolecularWeight>86.18</MolecularWeight>
<TlvBasisCriticalEffect>CNS impair; peripheral neuropathy; eye irr</TlvBasisCriticalEffect>
</AcgihTlvDetails>
<AvgPercent>20.000000</AvgPercent>
</Ingredients>
<Ingredients>
<ChemicalName>2-Propanone</ChemicalName>
<Cas>000067-64-1</Cas>
<Percent>30.000000</Percent>
<PercentMin>10.000000</PercentMin>
<PercentOperator>LessThanOrEqualTo</PercentOperator>
<PercentMinOperator>GreaterThanOrEqualTo</PercentMinOperator>
<PercentUnits>ByWeight</PercentUnits>
<PercentModifier xsi:nil="true" />
<MinPercent>10.000000</MinPercent>
<MaxPercent>30.000000</MaxPercent>
<Sara313Details>
<ChemicalKey>67641</ChemicalKey>
<IsPBT>false</IsPBT>
<IsSara313Toxic>false</IsSara313Toxic>
</Sara313Details>
<Sara302Details>
<ChemicalKey>67641</ChemicalKey>
<IsSara302Ehs>false</IsSara302Ehs>
</Sara302Details>
<OshaPelDetails>
<ChemicalKey>67641</ChemicalKey>
<OshaPelChemName>ACETONE</OshaPelChemName>
<Type>Z1</Type>
<Twa>1000</Twa>
<TwaUnits>unknown unit type</TwaUnits>
<TwaInMg>2400</TwaInMg>
<Stel xsi:nil="true" />
<CeilInPpm xsi:nil="true" />
<CeilInMg xsi:nil="true" />
<PeakInPpm xsi:nil="true" />
<PeakInMg xsi:nil="true" />
</OshaPelDetails>
<AcgihTlvDetails>
<ChemicalKey>67641</ChemicalKey>
<AcgihTlvChemName>ACETONE</AcgihTlvChemName>
<SkinDesignation>false</SkinDesignation>
<Sensitizer>false</Sensitizer>
<SimpleAsphyxiant>false</SimpleAsphyxiant>
<CarcinogenCategory>A4</CarcinogenCategory>
<YearKnowCarcinogen />
<ExposureByAllRoutes>false</ExposureByAllRoutes>
<Twa xsi:nil="true" />
<TwaInPpm>250</TwaInPpm>
<StelInPpm>500</StelInPpm>
<StelInMg xsi:nil="true" />
<CeilInPpm xsi:nil="true" />
<CeilInMg xsi:nil="true" />
<MolecularWeight>58.05</MolecularWeight>
<TlvBasisCriticalEffect>URT & eye irr; CNS impair</TlvBasisCriticalEffect>
</AcgihTlvDetails>
<AvgPercent>20.000000</AvgPercent>
</Ingredients>
<MsdsId>8672822</MsdsId>
<MsdsMfgName>Permatex USA</MsdsMfgName>
<MsdsProductName>118Da All Purpose Spray Adhesive 11 oz</MsdsProductName>
<Properties>
<PhysicalState>Aerosol</PhysicalState>
<BoilingPoint>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Celsius</Units>
<Value>38.0000</Value>
</BoilingPoint>
<FlashPoint>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Celsius</Units>
<Value>-18.0000</Value>
</FlashPoint>
<MolecularWeight xsi:nil="true" />
<Ph xsi:nil="true" />
<SpecificGravity>0.7300</SpecificGravity>
<VaporDensity xsi:nil="true" />
<Uel xsi:nil="true" />
<Lel xsi:nil="true" />
<BoilingPointInCelsius>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Celsius</Units>
<Value>38</Value>
</BoilingPointInCelsius>
<FlashPointInCelsius>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Celsius</Units>
<Value>-18</Value>
</FlashPointInCelsius>
<BoilingPointInFahrenheit>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Fahrenheit</Units>
<Value>100.4</Value>
</BoilingPointInFahrenheit>
<FlashPointInFahrenheit>
<Minimum xsi:nil="true" />
<Range>EqualTo</Range>
<Units>Fahrenheit</Units>
<Value>-0.399999999999999</Value>
</FlashPointInFahrenheit>
</Properties>
<RevisionDate>2015-05-18T00:00:00</RevisionDate>
<MsdsRevListId>3836824</MsdsRevListId>
<SdsConfirmationDate>2015-05-18T00:00:00</SdsConfirmationDate>
<ClassificationCompleted>true</ClassificationCompleted>
<CasCompleted>true</CasCompleted>
<PropertiesCompleted>true</PropertiesCompleted>
<Locale>en</Locale>
<DocumentFormat>Msds</DocumentFormat>
<Country>USA</Country>
<MsdsLanguage>en</MsdsLanguage>
<MsdsRegion>UnitedStates</MsdsRegion>
<SdsNotRequired>false</SdsNotRequired>
<MfgContactInfo>
<MfgAddress>6875 Parkland Boulevard</MfgAddress>
<MfgCity>Solon</MfgCity>
<MfgState>Ohio</MfgState>
<MfgCountry>United States</MfgCountry>
<MfgPostalCode>44139</MfgPostalCode>
<MfgPhoneCountryCode />
<MfgPhoneAreaCode>440</MfgPhoneAreaCode>
<MfgPhoneNumber>914-3571</MfgPhoneNumber>
<MfgPhoneExtension />
<MfgFaxCountryCode />
<MfgFaxAreaCode>440</MfgFaxAreaCode>
<MfgFaxNumber>914-3500</MfgFaxNumber>
<MfgFaxExtension />
<MfgEmail>denise.boyd#permatex.com</MfgEmail>
<MfgWebUrl>http://www.permatex.com</MfgWebUrl>
</MfgContactInfo>
<GhsClassification>
<SignalWord>None</SignalWord>
<SignalWordText>Danger</SignalWordText>
<Pictograms>
<Code>GHS02</Code>
</Pictograms>
<Pictograms>
<Code>GHS07</Code>
</Pictograms>
<Pictograms>
<Code>GHS08</Code>
</Pictograms>
<HazardClasses>
<HazardClassText>Flammable aerosol.</HazardClassText>
<CategoryText>Category 1</CategoryText>
<HazardClassPhraseTextID>92876</HazardClassPhraseTextID>
<CategoryPhraseTextID>93598</CategoryPhraseTextID>
<InternalHazardClassPhraseID>4059</InternalHazardClassPhraseID>
<InternalHazardClassPhraseLangCode>en</InternalHazardClassPhraseLangCode>
<InternalCategoryPhraseID>4082</InternalCategoryPhraseID>
<InternalCategoryPhraseLangCode>EN</InternalCategoryPhraseLangCode>
</HazardClasses>
<PCodes>
<SequenceNumber>401</SequenceNumber>
<Pcode>P405</Pcode>
<PcodeText>Store locked up.</PcodeText>
<PcodeSubTypeText>Storage</PcodeSubTypeText>
<PcodePhraseTextID>91288</PcodePhraseTextID>
<InternalPcodePhraseID>4009</InternalPcodePhraseID>
<InternalPcodePhraseLangCode>EN</InternalPcodePhraseLangCode>
</PCodes>
<HCodes>
<SequenceNumber>1</SequenceNumber>
<Hcode>H315</Hcode>
<HcodeText>Causes skin irritation.</HcodeText>
<HcodeSubTypeText>HealthHazard</HcodeSubTypeText>
<HcodePhraseTextID>91544</HcodePhraseTextID>
<InternalHcodePhraseID>4017</InternalHcodePhraseID>
<InternalHcodePhraseLangCode>EN</InternalHcodePhraseLangCode>
</HCodes>
<SignalWordPhraseTextID>236050</SignalWordPhraseTextID>
<InternalSignalWordPhraseId>22738</InternalSignalWordPhraseId>
<InternalSignalWordPhraseLangCode>EN</InternalSignalWordPhraseLangCode>
</GhsClassification>
<TransportationClassificationCompleted xsi:nil="true" />
<WasteCompleted xsi:nil="true" />
<ExtendedSds>false</ExtendedSds>
<TransportationExceptionClassificationCompleted xsi:nil="true" />
<BestAvailable>false</BestAvailable>
</Msds>
<ProductIdentifiers xmlns="http://3ecompany.com/webservices/catalogitemxml">
<Identifier>M007628</Identifier>
<Source>CPN</Source>
<FirstExportDate xsi:nil="true" />
<LastExportDate xsi:nil="true" />
<FlaggedForResend xsi:nil="true" />
</ProductIdentifiers>
<ProductName xmlns="http://3ecompany.com/webservices/catalogitemxml">118DA All Purpose Spray Adhesive - 82019 (10.5 oz aerosol)</ProductName>
<ProductUid xmlns="http://3ecompany.com/webservices/catalogitemxml">2501f87679eb40c5bff24e9e84170ff1</ProductUid>
<Locations xmlns="http://3ecompany.com/webservices/catalogitemxml">
<LocationUid>e504e4605e9c4da6a6243d617b45593f</LocationUid>
<Name>LUS Philadelphia (New Inventory)</Name>
<ChemicalApprovalStatus>None</ChemicalApprovalStatus>
<Quantity xsi:nil="true" />
<LocationPath>American Airlines > PHL > LUS Philadelphia (New Inventory)</LocationPath>
<ChemicalApprovalConditionalNotes />
<Notes />
<ActivatedBy>tehrman</ActivatedBy>
<ActivatedOn>2016-06-06T11:04:47.193</ActivatedOn>
</Locations>
<EeeProductId xmlns="http://3ecompany.com/webservices/catalogitemxml">3319854</EeeProductId>
<EeeCpcId xmlns="http://3ecompany.com/webservices/catalogitemxml">15071137</EeeCpcId>
<ConverterData xmlns="http://3ecompany.com/webservices/catalogitemxml" />
<CreatedBy xmlns="http://3ecompany.com/webservices/catalogitemxml">ondata</CreatedBy>
<CreatedDate xmlns="http://3ecompany.com/webservices/catalogitemxml">4/25/2016</CreatedDate>
<IsDeactivated xmlns="http://3ecompany.com/webservices/catalogitemxml">false</IsDeactivated>
<DeactivatedDate xsi:nil="true" xmlns="http://3ecompany.com/webservices/catalogitemxml" />
</CatalogItem>
</ArrayOfCatalogItem>';
And here's the query
WITH XMLNAMESPACES('http://3ecompany.com/webservices/catalogitemxml' AS i --Default on inner levels...
,'http://www.w3.org/2001/XMLSchema' AS xsd
,'http://www.w3.org/2001/XMLSchema-instance' AS xsi)
SELECT ci.value('#Version','int') AS CatalogVersion
,ci.value('(i:Container/i:ContainerSize/i:Value)[1]','decimal(15,9)') AS ContainerSizeValue
,ci.value('(i:Container/i:ContainerType)[1]','varchar(max)') AS ContainerType
--more values from Container-node
,ci.value('(i:Documents/#CultureCode)[1]','varchar(10)') AS DocumentCultureCode
--more attributes from Documents
--more elements on the same level
,ci.value('(i:Msds/i:Elink)[1]','varchar(max)') AS Msds_Elink
,ci.value('(i:Msds/i:FireCodeClassification/i:Asphyxiant)[1]','bit') AS Msds_FireCodeClassification_Asphyxiant
--more elements here
,ig.value('(i:ChemicalName)[1]','varchar(max)') AS Ingredients_ChemicalName
--more values for ingredients here
,ci.value('(i:Msds/i:MsdsId)[1]','bigint') AS Msds_Id
--more elements here
--and many more following this approach
FROM #xml.nodes('/ArrayOfCatalogItem/CatalogItem') AS A(ci)
CROSS APPLY A.ci.nodes('i:Msds/i:Ingredients') AS B(ig)

xml.value() method in SQL Server (Getting a value inside an XML query)

I have an XML Query like this:
<ChangeSet xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Change DateTime="2011-12-02T09:01:58.3615661-08:00" UserId="3123">
<Table ChangeType="Insert" Name="EVNT_LN_AFF">
<Keys>
<Key FieldName="DIR_CD" Value="NB" />
<Key FieldName="LN_ID" Value="A" />
<Key FieldName="EVNT_ID" Value="10T000289" />
</Keys>
<ChangedFields>
<Field FieldName="DIR_CD" Previous="" Current="NB" />
<Field FieldName="LN_ID" Previous="" Current="A" />
<Field FieldName="EVNT_ID" Previous="" Current="10T000289" />
<Field FieldName="UD_DTTM" Previous="" Current="12/2/2011 9:01:59 AM" />
<Field FieldName="UD_USER_ID" Previous="" Current="3123" />
</ChangedFields>
</Table>
(The query goes on)
Now I want to use a statement like this:
SELECT TOP 1000 [CHG_LOG_ID]
, [EVNT_ID]
, [DATA_XML_TXT]
, [UD_DTTM]
FROM [MY_PROJ].[dbo].[EVNT_CHG_LOG]
WHERE DATA_XML_TXT.value('(/ChangeSet/Change/Table/ChangedFields/UD_USER_ID)[0]','varchar(50)') like '%3123%'
But when I execute the query, I don't get any results.
I tested the following XQuery, and it should give you what you need:
SELECT TOP 1000 [CHG_LOG_ID]
, [EVNT_ID]
, [DATA_XML_TXT]
, [UD_DTTM]
FROM [MY_PROJ].[dbo].[EVNT_CHG_LOG]
WHERE DATA_XML_TXT.value('(/ChangeSet/Change/Table/ChangedFields/Field[#FieldName="UD_USER_ID"]/#Current)[1]','varchar(50)') like '%3123%'
Note: Indexing for XQuery starts at 1 instead of 0

Resources