XML Join in sql server - sql

I am trying to join the two xml response in stored procedure with the below mentioned code .The output that i was looking from my select query was
declare #cdoValuation xml
declare #marketColorPrice xml
set #cdoValuation = '<Response>
<CDOValuation id="BAB12-II.A2" mv="1.019358126500000e+002" run_date="2014-04-30T00:00:00" />
<CDOValuation id="BABS12-I.C" mv="9.915358793000000e+001" run_date="2014-04-30T00:00:00" />
<CDOValuation id="BLUEMTN.A2" mv="9.925446292000000e+001" run_date="2014-04-30T00:00:00" />
<CDOValuation id="BLUEMTN3.C" mv="9.472908099999999e+001" run_date="2014-04-30T00:00:00" />
<CDOValuation id="CGMS11-1.D" mv="9.644486014000000e+001" run_date="2014-04-30T00:00:00" />
<CDOValuation id="CSQUARE4.A" mv="9.880319818000000e+001" run_date="2014-04-30T00:00:00" />
<CDOValuation id="CSQUARE4.C" mv="9.295238056000000e+001" run_date="2014-04-30T00:00:00" />
<CDOValuation id="MADPK5.C" mv="9.735145883000000e+001" run_date="2014-04-30T00:00:00" />
<CDOValuation id="MADPK7.PS" mv="9.225345985000000e+001" run_date="2014-04-30T00:00:00" />
<CDOValuation id="MADPK8.A" mv="9.984445828000000e+001" run_date="2014-04-30T00:00:00" />
<CDOValuation id="OHAPARK.B" mv="9.652910265000000e+001" run_date="2014-04-30T00:00:00" />
<CDOValuation id="SDAYTONA.B2L" mv="9.590162241000000e+001" run_date="2014-04-30T00:00:00" />
</Response>'
set #marketColorPrice = '<Response>
<MarketColorPrice tranche_id="BAB12-II.A2" mk_price="1.001533333333333e+002" mk_date="2013-12-19T00:00:00" mk_source1="Empirasign/SCI" mk_source2="Cvr, Talk" mk_record_type="bwic, pxtalk" />
<MarketColorPrice tranche_id="BLUEMTN.A2" mk_price="9.877000000000000e+001" mk_date="2013-12-16T00:00:00" mk_source1="Empirasign/SCI" mk_source2="Cvr, Talk" mk_record_type="bwic, pxtalk" />
<MarketColorPrice tranche_id="BLUEMTN3.C" mk_price="8.050000000000000e+001" mk_date="2013-05-15T00:00:00" mk_source1="Empirasign/SCI" mk_source2="Talk, Trade" mk_record_type="bwic, pxtalk" />
<MarketColorPrice tranche_id="CSQUARE4.A" mk_price="9.765294117647059e+001" mk_date="2014-04-08T00:00:00" mk_source1="Empirasign/SCI" mk_source2="Cvr, Talk" mk_record_type="bwic, pxtalk" />
<MarketColorPrice tranche_id="CSQUARE4.C" mk_price="9.125000000000000e+001" mk_date="2014-05-15T00:00:00" mk_source1="Empirasign" mk_source2="Talk" mk_record_type="market" />
<MarketColorPrice tranche_id="MADPK5.C" mk_price="9.200000000000000e+001" mk_date="2013-10-24T00:00:00" mk_source1="SCI" mk_source2="Cvr" />
<MarketColorPrice tranche_id="MADPK7.PS" mk_price="1.133333333333333e+002" mk_date="2013-08-28T00:00:00" mk_source1="Empirasign/SCI" mk_source2="Cvr, Talk" mk_record_type="bwic, pxtalk" />
<MarketColorPrice tranche_id="OHAPARK.B" mk_price="9.787500000000000e+001" mk_date="2014-04-21T00:00:00" mk_source1="Empirasign" mk_source2="Talk" mk_record_type="market" />
</Response>'
declare #responseXml xml
set #responseXml =(select cdoValuation.cdoValuationcol.value('(//CDOValuation/#mv)[1]', 'float') as "#mv",
dbo.ToShortDateString(cdoValuation.cdoValuationcol.value('(//CDOValuation/#run_date)[1]', 'datetime')) as "#run_date",
marketColorPrice.marketColorPricecol.value('(//MarketColorPrice/#mk_price)[1]', 'float') as "#mk_price",
marketColorPrice.marketColorPricecol.value('(//MarketColorPrice/#mk_source1)[1]', 'varchar(30)') as "#mk_source1",
marketColorPrice.marketColorPricecol.value('(//MarketColorPrice/#mk_source2)[1]', 'varchar(30)') as "#mk_source2"
from #cdoValuation.nodes('/CDOValuation') cdoValuation(cdoValuationcol)
inner join #marketColorPrice.nodes('/MarketColorPrice') marketColorPrice(marketColorPricecol)
on marketColorPrice.marketColorPricecol.value('(//MarketColorPrice/tranche_id)[1]', 'VARCHAR(20)') =
cdoValuation.cdoValuationcol.value('(//CDOValuation/id)[1]', 'VARCHAR(20)') FOR XML PATH('BWICResult')
, ROOT('Response'))
select #responseXml
The output that i was expecting was of the following format but
doesnt seems to be the case .Can someone help me out to know as to what should be done ?
<Response> <BWICResult tranche_id="BAB12-II.A2" mv="1.019358126500000e+002" mk_price="1.001533333333333e+002"/> <BWICResult tranche_id="BLUEMTN.A2" mv="9.925446292000000e+001" mk_price="9.877000000000000e+001"/> </Response>

select C.X.value('#id', 'varchar(20)') as '#id',
C.X.value('#mv', 'float') as '#mv',
M.X.value('#mk_price', 'float') as '#mk_price'
from #cdoValuation.nodes('/Response/CDOValuation') as C(X)
inner join #marketColorPrice.nodes('Response/MarketColorPrice') as M(X)
on C.X.value('#id', 'varchar(20)') = M.X.value('#tranche_id', 'varchar(20)')
for xml path('BWICResult'), root('Response')
Result:
<Response>
<BWICResult id="BAB12-II.A2" mv="1.019358126500000e+002" mk_price="1.001533333333333e+002" />
<BWICResult id="BLUEMTN.A2" mv="9.925446292000000e+001" mk_price="9.877000000000000e+001" />
<BWICResult id="BLUEMTN3.C" mv="9.472908099999999e+001" mk_price="8.050000000000000e+001" />
<BWICResult id="CSQUARE4.A" mv="9.880319818000000e+001" mk_price="9.765294117647059e+001" />
<BWICResult id="CSQUARE4.C" mv="9.295238056000000e+001" mk_price="9.125000000000000e+001" />
<BWICResult id="MADPK5.C" mv="9.735145883000000e+001" mk_price="9.200000000000000e+001" />
<BWICResult id="MADPK7.PS" mv="9.225345985000000e+001" mk_price="1.133333333333333e+002" />
<BWICResult id="OHAPARK.B" mv="9.652910265000000e+001" mk_price="9.787500000000000e+001" />
</Response>

Related

replace XML variable in sql [duplicate]

This question already has answers here:
Updating SQL Server XML node
(2 answers)
Closed 4 years ago.
How do I replace the variable value of xml in sql? I need to change the values of ID and Text.
Sample XML
<Values>
<ValueList>
<Entry key="Num" type="Values">
<value ID="1" Text="One" />
</Entry>
<Entry key="Name" type="Values">
<value ID="2" Text="two" />
</Entry>
</ValueList>
</Values>
You can modified the ID value like following. Here I am updating ID="1" to "111", similarly you can change the text for a specific text using modify.
DECLARE #XML XML
SET #XML= '<Values> <ValueList> <Entry key="Num" type="Values"> <value ID="1" Text="One" /> </Entry> <Entry key="Name" type="Values"> <value ID="2" Text="two" /> </Entry> </ValueList> </Values>'
SET #XML.modify('replace value of (Values/ValueList/Entry/value[#ID eq ("1")]/#ID)[1] with ("1111")')
select #XML
If you want to use variables, it can be achieved like following.
DECLARE #XML XML
Declare #IDTOReplace VARCHAR(5)='1'
DECLARE #IDWithReplace VARCHAR(5) = '111'
SET #XML= '<Values> <ValueList> <Entry key="Num" type="Values"> <value ID="1" Text="One" /> </Entry> <Entry key="Name" type="Values"> <value ID="2" Text="two" /> </Entry> </ValueList> </Values>'
SET #XML.modify('replace value of (Values/ValueList/Entry/value[#ID eq sql:variable("#IDTOReplace")]/#ID)[1] with sql:variable("#IDWithReplace")')
select #XML
If you want to change the Text based on some Id, it can be achieved like following.
DECLARE #XML XML
Declare #IDTOReplace VARCHAR(5)='1'
DECLARE #TextToReplace VARCHAR(100) = 'NewText'
SET #XML= '<Values> <ValueList> <Entry key="Num" type="Values"> <value ID="1" Text="One" /> </Entry> <Entry key="Name" type="Values"> <value ID="2" Text="two" /> </Entry> </ValueList> </Values>'
SET #XML.modify('replace value of (Values/ValueList/Entry/value[#ID eq sql:variable("#IDTOReplace")]/#Text)[1] with sql:variable("#TextToReplace")')
select #XML

Mule - finding the sum of the values of xml elements

I need to find the sume of the xml elements in mule. The input xml looks like this :
<message:MessageGroup
xmlns:message="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message"
xmlns="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/generic"
xmlns:common="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/common"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/generic http://www.sdmx.org/docs/2_0/SDMXGenericData.xsd http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message http://www.sdmx.org/docs/2_0/SDMXMessage.xsd">
<Header xmlns="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message">
<ID>none</ID>
<Test>false</Test>
<Truncated>false</Truncated>
<Prepared>2017-08-28T05:35:50</Prepared>
<Sender id="ABS">
<Name xml:lang="en">Australian Bureau of Statistics</Name>
<Name xml:lang="fr">Australian Bureau of Statistics</Name>
</Sender>
</Header>
<DataSet
keyFamilyURI="http://stat.data.abs.gov.au/restsdmx/sdmx.ashx/GetKeyFamily/CPI">
<KeyFamilyRef>CPI</KeyFamilyRef>
<Series>
<SeriesKey>
<Value concept="MEASURE" value="3" />
<Value concept="REGION" value="50" />
<Value concept="INDEX" value="10001" />
<Value concept="TSEST" value="10" />
<Value concept="FREQUENCY" value="Q" />
</SeriesKey>
<Attributes>
<Value concept="TIME_FORMAT" value="P3M" />
</Attributes>
<Obs>
<Time>2001-Q1</Time>
<ObsValue value="6" />
</Obs>
<Obs>
<Time>2001-Q2</Time>
<ObsValue value="6.1" />
</Obs>
<Obs>
<Time>2001-Q3</Time>
<ObsValue value="2.5" />
</Obs>
<Obs>
<Time>2001-Q4</Time>
<ObsValue value="3.1" />
</Obs>
<Obs>
<Time>2002-Q1</Time>
<ObsValue value="3" />
</Obs>
<Obs>
<Time>2002-Q2</Time>
<ObsValue value="2.8" />
</Obs>
<Obs>
<Time>2002-Q3</Time>
<ObsValue value="3.2" />
</Obs>
<Obs>
<Time>2002-Q4</Time>
<ObsValue value="2.9" />
</Obs>
</Series>
<Annotations>
<common:Annotation>
<common:AnnotationTitle>Statistical usage warning
</common:AnnotationTitle>
<common:AnnotationText>
ABS.Stat beta is continuing to be developed. Data will be updated as soon
as possible following its 11:30 am release on the ABS website.
</common:AnnotationText>
</common:Annotation>
</Annotations>
</DataSet>
Here I need to do sum of the elements : which is inside : MessageGroup.DataSet.Series.*Obs. Tried doing using dataweave but was unsuccessful. While using dataweave I am not able to value of . Any help will be appreciated.
As values are attributes of ObsValue tag use # sign to get attribute value like,
%dw 1.0
%output application/java
---
sum (payload.MessageGroup.DataSet.Series.*Obs.ObsValue.#value)
Output = 29.6
Hope this helps

Selecting values out of XML with SQL Server 2012 with nested namespaces

My XML looks like
<?xml version="1.0" encoding="UTF-8"?>
<ListasExternasFull xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Encabezado xmlns="http://tempuri.org/">
<Acceso>true</Acceso>
<Usuario>FENALCO</Usuario>
<Contrasena>FENALCO2015PROD</Contrasena>
<Documento>24944511</Documento>
<TipoDocumento>1</TipoDocumento>
<Nombres />
<Apellidos />
<Login />
<Fecha>2016-01-23T17:07:56.1986626-05:00</Fecha>
<IdConsulta>0</IdConsulta>
</Encabezado>
<objContraloria xmlns="http://tempuri.org/">
<Id>92798</Id>
<IsContraloria>false</IsContraloria>
<Cedula>24944511</Cedula>
<Nombre />
<Departamento />
<Municipio />
<EntidadAfectada />
<FallosACargo />
<TipoResponsabilidad />
<TipoPersona />
<ReportadoPor />
<FechaControl>2016-01-23T17:03:43.13</FechaControl>
<Excepcion />
</objContraloria>
<objFosyga xmlns="http://tempuri.org/">
<Id>92496</Id>
<IsFosyga>false</IsFosyga>
<NumeroIdentidad>24944511</NumeroIdentidad>
<Nombre />
<Apellido />
<Departamento />
<Municipio />
<Estado />
<Entidad />
<Regimen />
<FechaAfiliacion />
<TipoAfiliado />
<FechaControl>2016-01-23T17:07:56.285612-05:00</FechaControl>
<Excepcion>Se generó un error al consultar la lista. Por favor intente mas tarde o contacte a su administrador.</Excepcion>
</objFosyga>
<objOfac xmlns="http://tempuri.org/">
<Id>91950</Id>
<Cedula>24944511</Cedula>
<Nombre />
<Direccion />
<Tipo />
<Programa />
<Score />
<FechaControl>2016-01-23T17:03:43.097</FechaControl>
<Lista />
<Excepcion />
<IsOfac>false</IsOfac>
</objOfac>
<objPolicia xmlns="http://tempuri.org/">
<Id>93113</Id>
<Cedula>24944511</Cedula>
<Nombre />
<IsAntecedentes>false</IsAntecedentes>
<IsRegistrado>false</IsRegistrado>
<Mensaje />
<FechaControl>2016-01-23T17:08:17.3118339-05:00</FechaControl>
<IsPolicia>false</IsPolicia>
<Excepcion>Se generó un error al consultar la lista. Por favor intente mas tarde o contacte a su administrador.</Excepcion>
</objPolicia>
<objRues xmlns="http://tempuri.org/">
<Id>91297</Id>
<TipoID />
<Nit>24944511</Nit>
<RazonSocial />
<Descripcion_Camara />
<Descripcion_Categoria_Matricula />
<Fecha_Matricula />
<IsRM>false</IsRM>
<IsRUP>false</IsRUP>
<IsESAL>false</IsESAL>
<IsRNT>false</IsRNT>
<FechaControl>2016-01-23T17:03:43.473</FechaControl>
<IsRUES>false</IsRUES>
<Excepcion />
</objRues>
<objSim xmlns="http://tempuri.org/">
<Id>92657</Id>
<Cedula>24944511</Cedula>
<NoRadicado />
<Identificador />
<FechaSolicitud />
<Estado />
<Resultado />
<DisponibleEntrega />
<Excepcion />
<FechaControl>2016-01-23T17:03:43.207</FechaControl>
<IsSim>false</IsSim>
</objSim>
<objSimit xmlns="http://tempuri.org/">
<Id>92905</Id>
<Cedula>24944511</Cedula>
<Infractor />
<Resolucion />
<FechaResolucion />
<Comparendo />
<FechaComparendo />
<Secretaria />
<Estado />
<Infraccion />
<ValorMulta />
<InteresMora />
<ValorAdicional />
<ValorPagar />
<FechaControl>2016-01-23T17:03:43.55</FechaControl>
<IsSimit>false</IsSimit>
<Excepcion />
</objSimit>
<objSisben xmlns="http://tempuri.org/">
<Id>94783</Id>
<IsSisben>true</IsSisben>
<NumeroDocumento>24944511</NumeroDocumento>
<Nombres>MARIA ISLENY</Nombres>
<Apellidos>RODAS DE FRANCO</Apellidos>
<TipoDocumento>Cédula de Ciudadanía</TipoDocumento>
<Departamento>RISARALDA</Departamento>
<Municipio>PEREIRA</Municipio>
<Area>1</Area>
<Ficha>10097</Ficha>
<Puntaje>47,86</Puntaje>
<FechaModificacion>2015/03/05</FechaModificacion>
<Estado>VALIDADO</Estado>
<FechaControl>2016-01-23T17:03:43.287</FechaControl>
<Excepcion />
</objSisben>
<objRuaf xmlns="http://tempuri.org/">
<Id>84066</Id>
<IsRuaf>true</IsRuaf>
<TipoIdentificacion>CC</TipoIdentificacion>
<Identificacion>24944511</Identificacion>
<Nombre>MARIA ISLENY RODAS DE FRANCO</Nombre>
<Sexo>FEMENINO</Sexo>
<UbicacionAfiliacion>RISARALDA - PEREIRA</UbicacionAfiliacion>
<EstadoAfiliado>ACTIVO</EstadoAfiliado>
<Administradora>NUEVA EPS SA</Administradora>
<Regimen>SALUD: CONTRIBUTIVO</Regimen>
<FechaAfiliacion>2015-08-01</FechaAfiliacion>
<TipoAfiliado>BENEFICIARIO</TipoAfiliado>
<FechaControl>2016-01-23T17:03:45.207</FechaControl>
<Observacion />
<Excepcion />
</objRuaf>
<objDisponibilidad xmlns="http://tempuri.org/">
<Fosyga>true</Fosyga>
<Sisben>true</Sisben>
<Ofac>true</Ofac>
<Policia>true</Policia>
<Rues>true</Rues>
<Sim>true</Sim>
<Simit>true</Simit>
<Contraloria>true</Contraloria>
<Onu>true</Onu>
<Ruaf>true</Ruaf>
</objDisponibilidad>
</ListasExternasFull>
and I can not get reach to consult the objRuaf/Identificacion node due to nested namespaces aguin I can help with a query to reach these nodes
Declare default XML namespace WITH XMLNAMESPACES (DEFAULT 'http://tempuri.org/'):
;WITH XMLNAMESPACES (DEFAULT 'http://tempuri.org/')
SELECT val = s.c.value('.', 'NVARCHAR(100)')
FROM #x.nodes('//objRuaf/Identificacion') AS s(c);
LiveDemo
Or:
;WITH XMLNAMESPACES ('http://tempuri.org/' AS a)
SELECT val = s.c.value('.', 'NVARCHAR(100)')
FROM #x.nodes('//a:objRuaf/a:Identificacion') AS s(c)

How to get value from XML in stored procedure?

Can you all help me for this problem?
I want to get value from following XML in sql stored procedure. I don't get vlaue if 'xsi:type="ActiveDirectoryItem"' is in tag 'anyType', and 'ActiveDirectoryItems' tag is also with URLs. How can i do to get only values?
<?xml version="1.0" encoding="utf-8" ?>
<ActiveDirectoryItems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<Items>
<anyType xsi:type="ActiveDirectoryItem">
<FirstName />
<MiddleInitial />
<LastName />
<DisplayName>Migrate-group</DisplayName>
<UserPrincipalName />
<PostalAddress />
<ResidentialAddress />
<Title />
<HomePhone />
<OfficePhone />
<Mobile />
<Fax />
<Email>Migrate-group#gmail.com</Email>
<Url />
<AccountName>Migrate-group</AccountName>
<DistinguishedName />
<IsAccountActive>false</IsAccountActive>
<ManagedBy />
<Manager />
<CompareType>0</CompareType>
<Description />
<Department />
<Company />
<Type />
</anyType>
</Items>
<GlobalCatalog />
</ActiveDirectoryItems>
The format i want to get is as the following:
DisplayName Email Account Name
Migrate-group Migrate-group#gmail.com Migrate-group
you can use the value keyword
Example:
DECLARE #MyXml XML = '<Root><SomeData>100</SomeData></Root>'
DECLARE #Something INT
SELECT #Something = #MyXml.value('(//Root/SomeData)[1]', 'INT')

sp_xml_preparedocument go with error "Only one top level element is allowed in an XML document"

I'am trying to execute sp_xml_preparedocument and geting error "Only one top level element is allowed in an XML document"
my T-SQL commands:
DECLARE #aa XML
DECLARE #idoc int
SET #aa =(select * from db_name for xml auto, xmldata)
#aa now is
<Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes" name="Schema7">
<ElementType name="Person" content="empty" model="closed">
<AttributeType name="preson_id" dt:type="i4" />
<AttributeType name="Name" dt:type="string" />
<AttributeType name="Surname" dt:type="string" />
<AttributeType name="guid" dt:type="uuid" />
<AttributeType name="version" dt:type="bin.base64" />
<attribute type="preson_id" />
<attribute type="Name" />
<attribute type="Surname" />
<attribute type="guid" />
<attribute type="version" />
</ElementType>
</Schema>
<Person xmlns="x-schema:#Schema7" preson_id="1" Name="Иван" Surname="Иванов" guid="2E739E87-3CA4-4ED8-ADD0-8B59957668B8" version="AAAAAAAAB9E=" />
<Person xmlns="x-schema:#Schema7" preson_id="2" Name="Николай" Surname="Николаев" guid="BDC41C59-D70F-4B70-954E-4918B9516AF8" version="AAAAAAAAB9I=" />
<Person xmlns="x-schema:#Schema7" preson_id="3" Name="Максим" Surname="Максимов" guid="740E57F3-56BA-48B8-92AF-978D7B1D2712" version="AAAAAAAAB9M=" />
EXEC sp_xml_preparedocument #idoc OUTPUT, #aa
The XML parse error 0xc00ce555 occurred on line number 1, near the XML text ""
Msg 6602, Level 16, State 2, Procedure sp_xml_preparedocument, Line 1
The error description is 'Only one top level element is allowed in an XML document
I'am new in this, and i need help)))
An one more question - How parse timestamp type?
if i use
SET #aa =(select * from db_name for xml elements, root('root'), type)
sp_xml_preparedocument works fine, OPENXML returns all values of my db_table, but timestamp values looks not the same as were..
Sorry for my bad English
SELECT #aa returns
<Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes" name="Schema7">
<ElementType name="Person" content="empty" model="closed">
<AttributeType name="preson_id" dt:type="i4" />
<AttributeType name="Name" dt:type="string" />
<AttributeType name="Surname" dt:type="string" />
<AttributeType name="guid" dt:type="uuid" />
<AttributeType name="version" dt:type="bin.base64" />
<attribute type="preson_id" />
<attribute type="Name" />
<attribute type="Surname" />
<attribute type="guid" />
<attribute type="version" />
</ElementType>
</Schema>
<Person xmlns="x-schema:#Schema7" preson_id="1" Name="Иван" Surname="Иванов" guid="2E739E87-3CA4-4ED8-ADD0-8B59957668B8" version="AAAAAAAAB9E=" />
<Person xmlns="x-schema:#Schema7" preson_id="2" Name="Николай" Surname="Николаев" guid="BDC41C59-D70F-4B70-954E-4918B9516AF8" version="AAAAAAAAB9I=" />
<Person xmlns="x-schema:#Schema7" preson_id="3" Name="Максим" Surname="Максимов" guid="740E57F3-56BA-48B8-92AF-978D7B1D2712" version="AAAAAAAAB9M=" />
An XML document must have one root element only - see W3C specification.
Thus in you case if Schema is the root element you cannot add the Person elements at the end
Make sure that there is no duplicate entries for the record that you are trying to get