Select nodes/value from XML that uses namespace - sql

I would like to select this line from my XML:
<komentarz>Nieprawidłowy parametr - IdTabeliRekorduZrodlowego</komentarz>
My code and XML looks like:
DECLARE #XML XML
DECLARE #NRZAM VARCHAR(4000)
SET #XML = '
<tns:powiadom
xmlns:ns3="http://cyfrowypolsat.pl/interfejsy/zgody/v4/zgodyKlienckie"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tns="http://cyfrowypolsat.pl/uslugi/powiadomienia/v2/PowiadomieniaZwrotne">
<nazwaKwalifikowanaInterfejsuWywolywanego xmlns:ns3="http://cyfrowypolsat.pl/interfejsy/zgody/v4/zgodyKlienckie" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://cyfrowypolsat.pl/uslugi/powiadomienia/v2/PowiadomieniaZwrotne">{http://cyfrowypolsat.pl/interfejsy/zgody/v4/zgodyKlienckie}zarejestrujStanZgodyAsync</nazwaKwalifikowanaInterfejsuWywolywanego>
<odpowiedz xmlns:ns3="http://cyfrowypolsat.pl/interfejsy/zgody/v4/zgodyKlienckie" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://cyfrowypolsat.pl/uslugi/powiadomienia/v2/PowiadomieniaZwrotne" xsi:type="ns3:OdpowiedzZgod">
<uid>EEE5A475-ECF5-4DBD-AB4E-7AB6442A4D6D</uid>
<status>BLAD</status>
<stanZgodyStatus xmlns:ns3="http://cyfrowypolsat.pl/interfejsy/zgody/v4/zgodyKlienckie" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://cyfrowypolsat.pl/uslugi/powiadomienia/v2/PowiadomieniaZwrotne">
<idPoziomy>4</idPoziomy>
<idReferencji>114601901</idReferencji>
<idTypyZgod>1110</idTypyZgod>
<kodBledu>14</kodBledu>
<komentarz>Nieprawidłowy parametr - IdTabeliRekorduZrodlowego</komentarz>
</stanZgodyStatus>
<stanZgodyStatus xmlns:ns3="http://cyfrowypolsat.pl/interfejsy/zgody/v4/zgodyKlienckie" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://cyfrowypolsat.pl/uslugi/powiadomienia/v2/PowiadomieniaZwrotne">
<idPoziomy>4</idPoziomy>
<idReferencji>114601901</idReferencji>
<idTypyZgod>1092</idTypyZgod>
<kodBledu>14</kodBledu>
<komentarz>Nieprawidłowy parametr - IdTabeliRekorduZrodlowego</komentarz>
</stanZgodyStatus>
</odpowiedz>
<odpowiedz xmlns:ns3="http://cyfrowypolsat.pl/interfejsy/zgody/v4/zgodyKlienckie" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://cyfrowypolsat.pl/uslugi/powiadomienia/v2/PowiadomieniaZwrotne" xsi:type="ns3:OdpowiedzZgod">
<uid>EEE5A475-ECF5-4DBD-AB4E-7AB6442A4D6D</uid>
<status>BLAD</status>
<stanZgodyStatus xmlns:ns3="http://cyfrowypolsat.pl/interfejsy/zgody/v4/zgodyKlienckie" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://cyfrowypolsat.pl/uslugi/powiadomienia/v2/PowiadomieniaZwrotne">
<idPoziomy>4</idPoziomy>
<idReferencji>114601901</idReferencji>
<idTypyZgod>1110</idTypyZgod>
<kodBledu>14</kodBledu>
<komentarz>Nieprawidłowy parametr - IdTabeliRekorduZrodlowego</komentarz>
</stanZgodyStatus>
<stanZgodyStatus xmlns:ns3="http://cyfrowypolsat.pl/interfejsy/zgody/v4/zgodyKlienckie" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://cyfrowypolsat.pl/uslugi/powiadomienia/v2/PowiadomieniaZwrotne">
<idPoziomy>4</idPoziomy>
<idReferencji>114601901</idReferencji>
<idTypyZgod>1092</idTypyZgod>
<kodBledu>14</kodBledu>
<komentarz>Nieprawidłowy parametr - IdTabeliRekorduZrodlowego</komentarz>
</stanZgodyStatus>
</odpowiedz>
<metryka xmlns:ns3="http://cyfrowypolsat.pl/interfejsy/zgody/v4/zgodyKlienckie" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://cyfrowypolsat.pl/uslugi/powiadomienia/v2/PowiadomieniaZwrotne">
<uzytkownik>sa</uzytkownik>
<system>SUZ</system>
<data>2018-12-17T10:38:12.880</data>
<uid>811ED2F9-1A71-4F9F-B858-A8EE256F6604</uid>
</metryka>
</tns:powiadom>
'
SET #NRZAM = (
SELECT TOP 1
x.Rec.query('komentarz').value('.','nvarchar(2000)') AS 'komentarz'
FROM
#XML.nodes('declare namespace
s="http://cyfrowypolsat.pl/interfejsy/zgody/v4/zgodyKlienckie";
s:powiadom/odpowiedz/stanZgodyStatus') AS x(Rec)
)
SELECT #XML
SELECT #NRZAM
My #NRZAM still is null but it would be 'Nieprawidłowy parametr - IdTabeliRekorduZrodlowego'. Wham am I doing wrong?

You're using the wrong namespace. Use the namespace for :tns like so:
SELECT x.Rec.query('komentarz').value('.','nvarchar(2000)') AS 'komentarz'
FROM #XML.nodes('declare namespace
s="http://cyfrowypolsat.pl/uslugi/powiadomienia/v2/PowiadomieniaZwrotne";
s:powiadom/odpowiedz/stanZgodyStatus'
) AS x(Rec)

Related

Find element or attribute value anywhere in XML

I am trying to find the value of an element / attribute regardless of where it exists in the XML.
XML:
<?xml version="1.0" encoding="UTF-8"?>
<cXML payloadID="12345677-12345567" timestamp="2017-07-26T09:11:05">
<Header>
<From>
<Credential domain="1212">
<Identity>01235 </Identity>
<SharedSecret/>
</Credential>
</From>
<To>
<Credential domain="1212">
<Identity>01234</Identity>
</Credential>
</To>
<Sender>
<UserAgent/>
<Credential domain="8989">
<Identity>10678</Identity>
<SharedSecret>Testing123</SharedSecret>
</Credential>
</Sender>
</Header>
<Request deploymentMode="Prod">
<ConfirmationRequest>
<ConfirmationHeader noticeDate="2017-07-26T09:11:05" operation="update" type="detail">
<Total>
<Money>0.00</Money>
</Total>
<Shipping>
<Description>Delivery</Description>
</Shipping>
<Comments>WO# generated</Comments>
</ConfirmationHeader>
<OrderReference orderDate="2017-07-25T15:22:11" orderID="123456780000">
<DocumentReference payloadID="5678-4567"/>
</OrderReference>
<ConfirmationItem quantity="1" lineNumber="1">
<ConfirmationStatus quantity="1" type="detail">
<ItemIn quantity="1">
<ItemID>
<SupplierPartID>R954-89</SupplierPartID>
</ItemID>
<ItemDetail>
<UnitPrice>
<Money currency="USD">0.00</Money>
</UnitPrice>
<Description>Test Descritpion 1</Description>
<UnitOfMeasure>QT</UnitOfMeasure>
</ItemDetail>
</ItemIn>
</ConfirmationStatus>
</ConfirmationItem>
<ConfirmationItem quantity="1" lineNumber="2">
<ConfirmationStatus quantity="1" type="detail">
<ItemIn quantity="1">
<ItemID>
<SupplierPartID>Y954-89</SupplierPartID>
</ItemID>
<ItemDetail>
<UnitPrice>
<Money currency="USD">0.00</Money>
</UnitPrice>
<Description>Test Descritpion 2</Description>
<UnitOfMeasure>QT</UnitOfMeasure>
</ItemDetail>
</ItemIn>
</ConfirmationStatus>
</ConfirmationItem>
</ConfirmationRequest>
</Request>
</cXML>
I want to get the value of the payloadID on the DocumentReference element. This is what I have tried so far:
BEGIN
Declare #Xml xml
Set #Xml = ('..The XML From Above..' as xml)
END
--no value comes back
Select c.value('(/*/DocumentReference/#payloadID)[0]','nvarchar(max)') from #Xml.nodes('//cXML') x(c)
--no value comes back
Select c.value('#payloadID','nvarchar(max)') from #Xml.nodes('/cXML/*/DocumentReference') x(c)
--check if element exists and it does
Select #Xml.exist('//DocumentReference');
I tried this in an xPath editor: //DocumentReference/#payloadID
This does work, but I am not sure what the equivalent syntax is in SQL
Calling .nodes() (like suggested in comment) is an unecessary overhead...
Better try it like this:
SELECT #XML.value('(//DocumentReference/#payloadID)[1]','nvarchar(max)')
And be aware, that XPath starts counting at 1. Your example with [0] cannot work...
--no value comes back
Select c.value('(/*/DocumentReference/#payloadID)[0]','nvarchar(max)') from...

xslt from two xml files using a matching node value

Kindly help me with the below expected output.I tried doing using for-each etc but ParentUUID1 is getting repeated for all RECORDS. I need to match the subscription_id key attribute from File2.xml with that in MainInput.xml and get the final expected output.
MainInput.xml
<?xml version="1.0" encoding="UTF-8" ?>
<qw:ACCOUNT_CHANGES xmlns:qw="http://xmlns.dummy.com/qwSubsResponse">
<qw:RECORD>
<qw:SUBSCRIPTION>
<qw:INFO key="subscriptionid_hash">abcd</qw:INFO>
<qw:INFO key="subscription_id">140172</qw:INFO>
<qw:INFO key="uuid">ParentUUID1</qw:INFO>
</qw:SUBSCRIPTION>
<qw:ALL_FO_ACCOUNTS>
<qw:FO_ACCOUNT>
<qw:FODATA key="subscription_id">140172</qw:FODATA>
<qw:FODATA key="uuid">uuidfouser1</qw:FODATA>
</qw:FO_ACCOUNT>
<qw:FO_ACCOUNT>
<qw:FODATA key="subscription_id">140172</qw:FODATA>
<qw:FODATA key="uuid">uuidfouser1</qw:FODATA>
</qw:FO_ACCOUNT>
</qw:ALL_FO_ACCOUNTS>
<qw:Platform>plat1</qw:Platform>
<qw:skip_subscription>1</qw:skip_subscription>
</qw:RECORD>
<qw:RECORD>
<qw:SUBSCRIPTION>
<qw:INFO key="subscriptionid_hash">xyz</qw:INFO>
<qw:INFO key="subscription_id">140</qw:INFO>
<qw:INFO key="uuid">ParentUUID2</qw:INFO>
</qw:SUBSCRIPTION>
<qw:ALL_FO_ACCOUNTS>
<qw:FO_ACCOUNT>
<qw:FODATA key="subscription_id">140</qw:FODATA>
<qw:FODATA key="uuid">uuidrcd2</qw:FODATA>
</qw:FO_ACCOUNT>
</qw:ALL_FO_ACCOUNTS>
<qw:Platform>plat1</qw:Platform>
<qw:skip_subscription>1</qw:skip_subscription>
</qw:RECORD>
</qw:ACCOUNT_CHANGES>
File2.xml
<?xml version="1.0" encoding="UTF-8" ?>
<qw:ACCOUNT_CHANGES xmlns:qw="http://xmlns.dummy.com/qwSubsResponse">
<qw:RECORD>
<qw:ALL_FO_ACCOUNTS>
<qw:FO_ACCOUNT>
<qw:FODATA key="subscription_id">140172</qw:FODATA>
<qw:FODATA key="uuid">uuidfouser1</qw:FODATA>
</qw:FO_ACCOUNT>
<qw:FO_ACCOUNT>
<qw:FODATA key="subscription_id">140172</qw:FODATA>
<qw:FODATA key="uuid">uuidfouser1</qw:FODATA>
</qw:FO_ACCOUNT>
</qw:ALL_FO_ACCOUNTS>
<qw:Platform>plat1</qw:Platform>
<qw:skip_subscription>1</qw:skip_subscription>
</qw:RECORD>
<qw:RECORD>
<qw:ALL_FO_ACCOUNTS>
<qw:FO_ACCOUNT>
<qw:FODATA key="subscription_id">140</qw:FODATA>
<qw:FODATA key="uuid">uuidrcd2</qw:FODATA>
</qw:FO_ACCOUNT>
</qw:ALL_FO_ACCOUNTS>
<qw:Platform>plat1</qw:Platform>
<qw:skip_subscription>1</qw:skip_subscription>
</qw:RECORD>
</qw:ACCOUNT_CHANGES>
Expected output:
<?xml version = '1.0' encoding = 'UTF-8'?>
<ns1:ACCOUNT_CHANGES xmlns:ns1="http://xmlns.dummy.com/qwSubsResponse">
<ns1:RECORD>
<ns1:SUBSCRIPTION>
<ns1:INFO key="uuid">ParentUUID1</qw:INFO>
</ns1:SUBSCRIPTION>
<ns1:ALL_FO_ACCOUNTS>
<ns1:FO_ACCOUNT>
<ns1:FODATA key="subscription_id">140172</ns1:FODATA>
<ns1:FODATA key="uuid">uuidfouser1</ns1:FODATA>
</ns1:FO_ACCOUNT>
<ns1:FO_ACCOUNT>
<ns1:FODATA key="subscription_id">140172</ns1:FODATA>
<ns1:FODATA key="uuid">uuidfouser1</ns1:FODATA>
</ns1:FO_ACCOUNT>
</ns1:ALL_FO_ACCOUNTS>
</ns1:RECORD>
<ns1:RECORD>
<ns1:SUBSCRIPTION>
<ns1:INFO key="uuid">ParentUUID2</qw:INFO>
</ns1:SUBSCRIPTION>
<ns1:ALL_FO_ACCOUNTS>
<ns1:FO_ACCOUNT>
<ns1:FODATA key="subscription_id">140</ns1:FODATA>
<ns1:FODATA key="uuid">uuidrcd2</ns1:FODATA>
</ns1:FO_ACCOUNT>
</ns1:ALL_FO_ACCOUNTS>
</ns1:RECORD>
</ns1:ACCOUNT_CHANGES>

ORA-19228: XPST0008 - undeclared identifier in oracle sql

I have xml string which i have mentioned below and i want to extract code from xml string. I have written below select query to extract the value from <ax2140:code>0</ax2140:code> which is 0 but i am getting error as
ORA-19228: XPST0008 - undeclared identifier: prefix 'ax2140' local-name 'ax2140:code'
19228. 00000 - "XPST0008 - undeclared identifier: prefix '%s' local-name '%s'"
Here is my xml string-
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:placeShopOrderResponse xmlns:ns="http://service.soap.CDRator.com">
<ns:return xmlns:ax2127="http://data.soap.CDRator.com/xsd"
xmlns:ax2129="http://webshop.data.soap.CDRator.com/xsd"
xmlns:ax2130="http://core.data.soap.CDRator.com/xsd"
xmlns:ax2133="http://signup.data.soap.CDRator.com/xsd"
xmlns:ax2134="http://core.signup.data.soap.CDRator.com/xsd"
xmlns:ax2139="http://result.service.soap.CDRator.com/xsd"
xmlns:ax2140="http://core.result.service.soap.CDRator.com/xsd"
xmlns:ax2147="http://webshop.result.service.soap.CDRator.com/xsd"
xmlns:ax2148="http://mandate.result.service.soap.CDRator.com/xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ax2147:PlaceShopOrderResultDTO">
<ax2130:id xsi:nil="true" />
<ax2140:code>0</ax2140:code>
<ax2140:description>OK</ax2140:description>
<ax2127:statusId>1</ax2127:statusId>
<ax2127:subscriptionCondition xsi:type="ax2127:SubscriptionStatusDTO">
<ax2130:id xsi:nil="true" />
<ax2140:code>0</ax2140:code>
<ax2140:description>OK</ax2140:description>
<ax2130:imsi xsi:nil="true" />
<ax2130:phoneNumber>NO_NUMBER</ax2130:phoneNumber>
<ax2127:imei xsi:nil="true" />
<ax2127:simCard xsi:nil="true" />
</ax2127:teleService>
</ax2147:subscriptions>
</ns:return>
</ns:placeShopOrderResponse>
</soapenv:Body>
</soapenv:Envelope>
Here is my select query:
SELECT ID,xt_code.CODE
FROM TEMP_SOAP_MONITORING_MSP sm
CROSS JOIN XMLTable(XMLNAMESPACES (
'http://core.result.service.soap.CDRator.com/xsd' as "ax2140_code"
),
'for $i in //ax2140:code return $i'
passing XMLType(sm.RESPONSE_XML)
columns "CODE" VARCHAR2(50) path '/') xt_code;
Use "ax2140" instead of "ax2140_code" in the query.

how to get xsd element format result from sql script

I need to create xml files to migrate a huge amount of data from one database to another database.
How to get result xsd format as below from ms sql script query?
Please share if you have any idea.
The xml file format is below:
<Batch>
<retail:customer xmlns:core="http://www.bactor.com/core" xmlns:retail=""http://www.bactor.com/retail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<retail:addresses>
<retail:address>
<retail:country>GB</retail:country>
<retail:countryCodeId></retail:countryCodeId>
<retail:isPreferred>true</retail:isPreferred>
<retail:isActive>true</retail:isActive>
<retail:typeId>PERSONAL_ADDRESS</retail:typeId>
<retail:postCode>2344</retail:postCode>
<retail:street1>1234214</retail:street1>
<retail:isTemplate>false</retail:isTemplate>
<retail:referenceId></retail:referenceId>
<retail:addressReferenceId>0727-:83f5bd9f331:e8e438a1:fa34668911272008</retail:addressReferenceId>
</retail:address>
</retail:addresses>
<retail:contactMethod></retail:contactMethod>
<retail:contactable>false</retail:contactable>
<retail:maritalStatus></retail:maritalStatus>
<retail:nationality></retail:nationality>
<retail:noChildren>0</retail:noChildren>
<retail:customerNumber>1</retail:customerNumber>
<retail:emailAddresses>
<retail:emailAddress>alice#wonderland.hearts</retail:emailAddress>
<retail:preferred>true</retail:preferred>
<retail:restrictedReason></retail:restrictedReason>
<retail:status></retail:status>
<retail:typeId>PERSONAL_EMAIL</retail:typeId>
<retail:referenceId></retail:referenceId>
<retail:active>false</retail:active>
</retail:emailAddresses>
<retail:phoneNumbers>
<retail:countryCode></retail:countryCode>
<retail:number>11222445566</retail:number>
<retail:preferred>true</retail:preferred>
<retail:restrictedReason></retail:restrictedReason>
<retail:status></retail:status>
<retail:typeId>LANDLINE</retail:typeId>
<retail:referenceId></retail:referenceId>
<retail:active>true</retail:active>
<retail:phoneNumberReferenceId>e437-:83f5bd9f331:e8e438a1:fa34668911272008</retail:phoneNumberReferenceId>
</retail:phoneNumbers>
<retail:customerName>
<retail:surname>AppleGate</retail:surname>
<retail:forename>Alice</retail:forename>
<retail:title>Mrs</retail:title>
<retail:sex>FEMALE</retail:sex>
<retail:dateOfBirth>2012-09-12T00:00:00+01:00</retail:dateOfBirth>
</retail:customerName>
<retail:businessContactMethod></retail:businessContactMethod>
<retail:preferredContactTime></retail:preferredContactTime>
<retail:allowInternalMarketing>true</retail:allowInternalMarketing>
<retail:allowExternalMarketing>true</retail:allowExternalMarketing>
<retail:employeeKey></retail:employeeKey>
<retail:customerType>RETAIL</retail:customerType>
<retail:organisation></retail:organisation>
<retail:taxIdentification></retail:taxIdentification>
<retail:companyNumber></retail:companyNumber>
<retail:createdBy></retail:createdBy>
<retail:createdAt></retail:createdAt>
<retail:status>New</retail:status>
<retail:source></retail:source>
</retail:customer>
<retail:customer xmlns:core="http://www.enactor.com/core" xmlns:retail="http://www.enactor.com/retail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<retail:addresses>
<retail:address>
<retail:country>GB</retail:country>
<retail:countryCodeId></retail:countryCodeId>
<retail:isPreferred>true</retail:isPreferred>
<retail:isActive>true</retail:isActive>
<retail:typeId>PERSONAL_ADDRESS</retail:typeId>
<retail:postCode>2344</retail:postCode>
<retail:street1>1234214</retail:street1>
<retail:isTemplate>false</retail:isTemplate>
<retail:referenceId></retail:referenceId>
<retail:addressReferenceId>0727-:83f5bd9f331:e8e438a1:fa34668911272008</retail:addressReferenceId>
</retail:address>
</retail:addresses>
<retail:contactMethod></retail:contactMethod>
<retail:contactable>false</retail:contactable>
<retail:maritalStatus></retail:maritalStatus>
<retail:nationality></retail:nationality>
<retail:noChildren>0</retail:noChildren>
<retail:customerNumber>1</retail:customerNumber>
<retail:emailAddresses>
<retail:emailAddress>alice#wonderland.hearts</retail:emailAddress>
<retail:preferred>true</retail:preferred>
<retail:restrictedReason></retail:restrictedReason>
<retail:status></retail:status>
<retail:typeId>PERSONAL_EMAIL</retail:typeId>
<retail:referenceId></retail:referenceId>
<retail:active>false</retail:active>
</retail:emailAddresses>
<retail:phoneNumbers>
<retail:countryCode></retail:countryCode>
<retail:number>11222445566</retail:number>
<retail:preferred>true</retail:preferred>
<retail:restrictedReason></retail:restrictedReason>
<retail:status></retail:status>
<retail:typeId>LANDLINE</retail:typeId>
<retail:referenceId></retail:referenceId>
<retail:active>true</retail:active>
<retail:phoneNumberReferenceId>e437-:83f5bd9f331:e8e438a1:fa34668911272008</retail:phoneNumberReferenceId>
</retail:phoneNumbers>
<retail:customerName>
<retail:surname>AppleGate</retail:surname>
<retail:forename>Alice</retail:forename>
<retail:title>Mrs</retail:title>
<retail:sex>FEMALE</retail:sex>
<retail:dateOfBirth>2012-09-12T00:00:00+01:00</retail:dateOfBirth>
</retail:customerName>
<retail:businessContactMethod></retail:businessContactMethod>
<retail:preferredContactTime></retail:preferredContactTime>
<retail:allowInternalMarketing>true</retail:allowInternalMarketing>
<retail:allowExternalMarketing>true</retail:allowExternalMarketing>
<retail:employeeKey></retail:employeeKey>
<retail:customerType>RETAIL</retail:customerType>
<retail:organisation></retail:organisation>
<retail:taxIdentification></retail:taxIdentification>
<retail:companyNumber></retail:companyNumber>
<retail:createdBy></retail:createdBy>
<retail:createdAt></retail:createdAt>
<retail:status>New</retail:status>
<retail:source></retail:source>
</retail:customer>
</Batch>
I am also trying with the below a pieces of sql script. but it is not working.
WITH XMLNAMESPACES ('http://www.enactor.com/retail' as ns1)
SELECT top 100 [id]
,[Title]
,[First_Name]
, RowNum = Row_NUMBER() OVER (Order by id)
FROM [Firinne].[dbo].[Contact] as Customer
For XML PATH('retail:Customer')
Try this:
DECLARE #xml XML
;WITH XMLNAMESPACES('http://www.w3.org/2001/XMLSchema-instance' AS xsi, 'http://www.bactor.com/retail' AS retail, 'http://www.bactor.com/core' AS core)
SELECT #xml = (SELECT
[retail:Customer].id AS [retail:id],
[retail:Customer].contactMethod AS [retail:contactMethod],
[retail:Customer].contactable AS [retail:contactable],
[retail:address].emailAddress AS [retail:emailAddress],
[retail:address].typeId AS [retail:typeId]
FROM dbo.Customers AS [retail:Customer]
JOIN dbo.emailAddresses AS [retail:address] ON [retail:Customer].id = [retail:address].customerID
FOR XML AUTO, ELEMENTS)
SET #xml = '<Batch>' + CAST(#xml AS NVARCHAR(max)) + '</Batch>'
SELECT #xml
Output:
<Batch>
<retail:Customer xmlns:core="http://www.bactor.com/core" xmlns:retail="http://www.bactor.com/retail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<retail:id>1</retail:id>
<retail:contactMethod>1</retail:contactMethod>
<retail:contactable>1</retail:contactable>
<retail:address>
<retail:emailAddress>some#some.some</retail:emailAddress>
<retail:typeId>1</retail:typeId>
</retail:address>
<retail:address>
<retail:emailAddress>some#some.some</retail:emailAddress>
<retail:typeId>2</retail:typeId>
</retail:address>
</retail:Customer>
<retail:Customer xmlns:core="http://www.bactor.com/core" xmlns:retail="http://www.bactor.com/retail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<retail:id>2</retail:id>
<retail:contactMethod>1</retail:contactMethod>
<retail:contactable>0</retail:contactable>
<retail:address>
<retail:emailAddress>some#some.some</retail:emailAddress>
<retail:typeId>3</retail:typeId>
</retail:address>
</retail:Customer>
</Batch>
EDIT:
You can do it like:
DECLARE #xml XML
;WITH XMLNAMESPACES('http://www.w3.org/2001/XMLSchema-instance' AS xsi, 'http://www.bactor.com/retail' AS retail, 'http://www.bactor.com/core' AS core)
SELECT #xml = (SELECT
[retail:Customer].id AS [retail:id],
[retail:Customer].contactMethod AS [retail:contactMethod],
[retail:Customer].contactable AS [retail:contactable],
(SELECT
[retail:address].emailAddress ,
[retail:address].typeId
FROM dbo.emailAddresses AS [retail:address] WHERE [retail:Customer].id = [retail:address].customerID
FOR XML AUTO, TYPE, ELEMENTS, ROOT('retail:Addresses')
)
FROM dbo.Customers AS [retail:Customer]
FOR XML AUTO, ELEMENTS)
SET #xml = '<Batch>' + CAST(#xml AS NVARCHAR(max)) + '</Batch>'
SELECT #xml
But namespaces are added to all child:
<Batch>
<retail:Customer xmlns:core="http://www.bactor.com/core" xmlns:retail="http://www.bactor.com/retail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<retail:id>1</retail:id>
<retail:contactMethod>1</retail:contactMethod>
<retail:contactable>1</retail:contactable>
<retail:Addresses xmlns:core="http://www.bactor.com/core" xmlns:retail="http://www.bactor.com/retail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<retail:address>
<emailAddress>some#some.some</emailAddress>
<typeId>1</typeId>
</retail:address>
<retail:address>
<emailAddress>some#some.some</emailAddress>
<typeId>2</typeId>
</retail:address>
</retail:Addresses>
</retail:Customer>
<retail:Customer xmlns:core="http://www.bactor.com/core" xmlns:retail="http://www.bactor.com/retail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<retail:id>2</retail:id>
<retail:contactMethod>1</retail:contactMethod>
<retail:contactable>0</retail:contactable>
<retail:Addresses xmlns:core="http://www.bactor.com/core" xmlns:retail="http://www.bactor.com/retail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<retail:address>
<emailAddress>some#some.some</emailAddress>
<typeId>3</typeId>
</retail:address>
</retail:Addresses>
</retail:Customer>
</Batch>
It is a known issue, and you can see details here:
https://connect.microsoft.com/SQLServer/feedback/details/265956/suppress-namespace-attributes-in-nested-select-for-xml-statements
Additional namespaces doesn't do any harm but increasing size of generated xml document.

insert an element to nth element in a xml in Sql Server

please consider this XML:
<Employees>
<Person>
<ID>1000</ID>
<Name>Nima</Name>
<LName>Agha</LName>
</Person>
<Person>
<ID>1001</ID>
<Name>Ligha</Name>
<LName>Ligha</LName>
</Person>
<Person>
<ID>1002</ID>
<Name>Jigha</Name>
<LName>Jigha</LName>
</Person>
<Person>
<ID>1003</ID>
<Name>Aba</Name>
<LName>Aba</LName>
</Person>
</Employees>
I want to write a procedure that get a number and then I insert an element to nth Person element. for example if 1 pass to my procedure I insert an element to first person element.
DECLARE #data XML =
'
<Employees>
<Person>
<ID>1000</ID>
<Name>Nima</Name>
<LName>Agha</LName>
</Person>
<Person>
<ID>1001</ID>
<Name>Ligha</Name>
<LName>Ligha</LName>
</Person>
<Person>
<ID>1002</ID>
<Name>Jigha</Name>
<LName>Jigha</LName>
</Person>
<Person>
<ID>1003</ID>
<Name>Aba</Name>
<LName>Aba</LName>
</Person>
</Employees>
'
DECLARE #offset INT = 2
DECLARE #value VARCHAR(100) = 'newvalue'
SET #data.modify('insert <NewAttribute>{sql:variable("#value")}</NewAttribute> as last into (/Employees/Person)[sql:variable("#offset")][1]')
SELECT #data
DECLARE #AttributeValue NVARCHAr(100) = 'TestValue';
DECLARE #NodeNR INT = 3
DECLARE #XML XML = '<Employees>
<Person>
<ID>1000</ID>
<Name>Nima</Name>
<LName>Agha</LName>
</Person>
<Person>
<ID>1001</ID>
<Name>Ligha</Name>
<LName>Ligha</LName>
</Person>
<Person>
<ID>1002</ID>
<Name>Jigha</Name>
<LName>Jigha</LName>
</Person>
<Person>
<ID>1003</ID>
<Name>Aba</Name>
<LName>Aba</LName>
</Person>
</Employees>';
SET #XML.modify('insert attribute Attribute {sql:variable("#AttributeValue")} into (/Employees/Person[position()=sql:variable("#NodeNr")])[1]')
Try this one -
DECLARE #Param INT = 1000
DECLARE #NodeID INT = 2
DECLARE #XML XML = '
<Employees>
<Person>
<ID>1000</ID>
<Name>Nima</Name>
<LName>Agha</LName>
</Person>
<Person>
<ID>1001</ID>
<Name>Ligha</Name>
<LName>Ligha</LName>
</Person>
<Person>
<ID>1002</ID>
<Name>Jigha</Name>
<LName>Jigha</LName>
</Person>
<Person>
<ID>1003</ID>
<Name>Aba</Name>
<LName>Aba</LName>
</Person>
</Employees>'
DECLARE #SQL NVARCHAR(MAX) = '
DECLARE #XML XML = #XML_Param
DECLARE #Id INT = #Value_Param
SET #XML.modify(''insert attribute Id {sql:variable("#Id")} into (/Employees/Person)[' + CAST(#NodeID AS VARCHAR) + ']'')
SELECT #XML_Output = #XML'
DECLARE #Definition NVARCHAR(500) =
N'#XML_Param XML, #Value_Param INT, #Node_Param INT, #XML_Output XML OUTPUT'
DECLARE #XMLResult XML
EXEC sys.sp_executesql
#SQL
, #Definition
, #XML_Param = #XML
, #Value_Param = #Param
, #Node_Param = 1
, #XML_Output = #XMLResult OUTPUT
SELECT #XMLResult