Parse an xml data column on a table in SQL Server 2012 - sql

How do I parse an xml column on a table of data in SQL Server 2012
Sample data
<GetOfferAvailabilityResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p3="http://somewebsite.com/v2.0" xmlns="http://somewebsite.com/v2.0" p3:TransactionID="281234567">
<p3:RuleResultList xsi:nil="true" />
<p3:ResultList>
<p3:ProviderResult p3:ProviderID="01" p3:ResultID="1234" p3:ResultType="NotAvailable" p3:ResultCode="NotAvailable" p3:BrokerID="55" p3:Structure="None">
<p3:EntityState>None</p3:EntityState>
<p3:ResultText>No Orders returned</p3:ResultText>
<p3:ShortDescription>Not Available</p3:ShortDescription>
<p3:LongDescription>We're sorry, but offers are currently not available for your service address.</p3:LongDescription>
<p3:ResultAction>ErrorMessage</p3:ResultAction>
<p3:SourceResultCode xsi:nil="true" />
</p3:ProviderResult>
</p3:ResultList>
</GetOfferAvailabilityResponse>'
I tried:
DECLARE #x xml
SET #x =
DECLARE #test TABLE (ID INT, XmlRule XML)
Insert into #test VALUES(1,'
<GetOfferAvailabilityResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" ---GetOfferAvailabilityResponse>')
When I use Select #test.query ('\') I get the entire xml but when I try Select #test.query ('\GetOfferAvailabilityResponse') I receive an empty result

You can try something like this:
DECLARE #XmlTbl TABLE (ID INT, XMLDATA XML)
INSERT INTO #XmlTbl
( ID, XMLDATA )
VALUES ( 1, '<GetOfferAvailabilityResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p3="http://somewebsite.com/v2.0" xmlns="http://somewebsite.com/v2.0" p3:TransactionID="281234567">
<p3:RuleResultList xsi:nil="true" />
<p3:ResultList>
<p3:ProviderResult p3:ProviderID="01" p3:ResultID="1234" p3:ResultType="NotAvailable" p3:ResultCode="NotAvailable" p3:BrokerID="55" p3:Structure="None">
<p3:EntityState>None</p3:EntityState>
<p3:ResultText>No Orders returned</p3:ResultText>
<p3:ShortDescription>Not Available</p3:ShortDescription>
<p3:LongDescription>We''re sorry, but offers are currently not available for your service address.</p3:LongDescription>
<p3:ResultAction>ErrorMessage</p3:ResultAction>
<p3:SourceResultCode xsi:nil="true" />
</p3:ProviderResult>
</p3:ResultList>
</GetOfferAvailabilityResponse>')
;WITH XMLNAMESPACES('http://somewebsite.com/v2.0' AS p3, DEFAULT 'http://somewebsite.com/v2.0')
SELECT
ProviderID = XmlData.value('(/GetOfferAvailabilityResponse/p3:ResultList/p3:ProviderResult/#p3:ProviderID)[1]', 'varchar(50)'),
EntityState = XmlData.value('(/GetOfferAvailabilityResponse/p3:ResultList/p3:ProviderResult/p3:EntityState)[1]', 'varchar(50)'),
ResultText = XmlData.value('(/GetOfferAvailabilityResponse/p3:ResultList/p3:ProviderResult/p3:ResultText)[1]', 'varchar(50)'),
ShortDescription = XmlData.value('(/GetOfferAvailabilityResponse/p3:ResultList/p3:ProviderResult/p3:ShortDescription)[1]', 'varchar(250)'),
LongDescription = XmlData.value('(/GetOfferAvailabilityResponse/p3:ResultList/p3:ProviderResult/p3:LongDescription)[1]', 'varchar(250)'),
ResultAction = XmlData.value('(/GetOfferAvailabilityResponse/p3:ResultList/p3:ProviderResult/p3:ResultAction)[1]', 'varchar(50)')
FROM
#XmlTbl
From a table that contains a column of type XML, select those bits and pieces that you need, taking into account the defined XML namespaces on your XML data
This gives me a result of:

Related

How do i get the `ResponseDescription` value in Microsoft Sql?

So the column i'm querying has an XML data that looks like this
<soap:Envelope xmlns:soap="http://google.com/">
<soap:Body>
<ns2:response xmlns:ns2="http://stackoverflow.com/">
<trackingId>1375321435</trackingId>
<responseCode>202</responseCode>
<responseDescription>Request completed successfully</responseDescription>
<detail><?xml version="1.0" encoding="UTF-8" standalone="yes"?> <LoanProcessResponse> <ResponseCode>E4284</ResponseCode> <ResponseDescription>The minimum value date allowed for this account must be greater than [08-12-2022].: acctDisburseTranLA.valueDate</ResponseDescription> <status>FAILURE</status> </LoanProcessResponse></detail>
</ns2:response>
</soap:Body>
</soap:Envelope>
and my query looks like the below
WITH XMLNAMESPACES('http://google.com/' AS soap, 'http://stackoverflow.com/' AS ns2)
SELECT
timeSent,
accountNo,
isSuccessful,
try_convert(xml, responsePayload).query('/soap:Envelope/soap:Body/ns2:response/detail/LoanProcessResponse/ResponseDescription') AS response
from my_table
where accountNo = '000000008'
ORDER BY timesent desc;
Can you help me get the value of the <ResponseDescription> without the tag?
Please try the following solution.
It is better to use XML data type for the responsePayload column.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (id INT IDENTITY PRIMARY KEY, responsePayload NVARCHAR(MAX));
INSERT #tbl (responsePayload) VALUES
(N'<soap:Envelope xmlns:soap="http://google.com/">
<soap:Body>
<ns2:response xmlns:ns2="http://stackoverflow.com/">
<trackingId>1375321435</trackingId>
<responseCode>202</responseCode>
<responseDescription>Request completed successfully</responseDescription>
<detail><?xml version="1.0" encoding="UTF-8" standalone="yes"?> <LoanProcessResponse> <ResponseCode>E4284</ResponseCode> <ResponseDescription>The minimum value date allowed for this account must be greater than [08-12-2022].: acctDisburseTranLA.valueDate</ResponseDescription> <status>FAILURE</status> </LoanProcessResponse></detail>
</ns2:response>
</soap:Body>
</soap:Envelope>');
-- DDL and sample data population, end
;WITH XMLNAMESPACES('http://google.com/' AS soap, 'http://stackoverflow.com/' AS ns2)
SELECT ID
, responseDescription = TRY_CAST(responsePayload AS XML)
.value('(/soap:Envelope/soap:Body/ns2:response/responseDescription/text())[1]', 'VARCHAR(200)')
FROM #tbl;
Output
ID
responseDescription
1
Request completed successfully

SQL Server: SELECT XML with Namespaces gives NULL Result

I want to load a XML File into SQL Server 2012 as a variable, one of the columns should contain the XML itself and the other columns should contain values from the XML elements.
My Issue is that I don't get an ERROR but also no record in my table, it just returned blank result
USE [testjrazt]
GO
DECLARE #doc XML
SELECT #doc = '<?xml version="1.0"?>
<SyncSalesOrder xmlns="http://schema.infor.com/InforOAGIS/2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schema.infor.com/InforOAGIS/2 http://schema.infor.com/2.12.x/InforOAGIS/BODs/SyncSalesOrder.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" releaseID="9.2" versionID="2.12.x">
<ApplicationArea>
<Sender>
<LogicalID>lid://infor.ln.dach_nausveln1_200_2</LogicalID>
<ComponentID>erp</ComponentID>
<ConfirmationCode>OnError</ConfirmationCode>
</Sender>
<CreationDateTime>2019-12-02T15:47:42Z</CreationDateTime>
<BODID>infor-nid:infor:200::AA0000008:?SalesOrder&verb=Sync</BODID>
</ApplicationArea>
<DataArea>
<Sync>
<TenantID>infor</TenantID>
<AccountingEntityID>200</AccountingEntityID>
<LocationID>
</LocationID>
<ActionCriteria>
<ActionExpression actionCode="Add"/>
</ActionCriteria>
</Sync>
<SalesOrder>
--CUT FOR BETTER READABILITY
</SalesOrder>
</DataArea>
</SyncSalesOrder>
'
--Inserting into COR_Outbox_Entry Tabelle -> I/O BOX
/*
INSERT INTO [dbo].[COR_OUTBOX_ENTRY]
([C_XML]
,[C_TENANT_ID]
,[C_MESSAGE_PRIORITY]
,[C_CREATED_DATE_TIME]
,[C_WAS_PROCESSED]
,[C_LOGICAL_ID])
*/
--Only SELECT to check if data get loaded from XML - BLANK RESULT
SELECT
i_xml = CAST (#doc AS varbinary(max)),
i_tenant_id = xdoc.value('(DataArea/Sync/TenantID)[1]','nvarchar(250)'), -- xpath /SyncSalesOrder/DataArea/Sync/TenantID
--i_message_priority =xdoc.value('()[1]','int'),
i_created_date_time = xdoc.value('(ApplicationArea/CreationDateTime)[1]','datetime'),
--i_was_processed = xdoc.value('()[1]','int'),
i_lid = xdoc.value('(ApplicationArea/Sender/LogicalID)[1]','nvarchar(250)')
FROM #doc.nodes('SyncSalesOrder') AS InputTable(xdoc)
Here is how to do it. Your XML has a default namespace. It should be taken into account via WITH XMLNAMESPACES clause.
-- DDL and sample data population, start
DECLARE #doc XML =
N'<SyncSalesOrder xmlns="http://schema.infor.com/InforOAGIS/2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://schema.infor.com/InforOAGIS/2 http://schema.infor.com/2.12.x/InforOAGIS/BODs/SyncSalesOrder.xsd"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" releaseID="9.2"
versionID="2.12.x">
<ApplicationArea>
<Sender>
<LogicalID>lid://infor.ln.dach_nausveln1_200_2</LogicalID>
<ComponentID>erp</ComponentID>
<ConfirmationCode>OnError</ConfirmationCode>
</Sender>
<CreationDateTime>2019-12-02T15:47:42Z</CreationDateTime>
<BODID>infor-nid:infor:200::AA0000008:?SalesOrder&verb=Sync</BODID>
</ApplicationArea>
<DataArea>
<Sync>
<TenantID>infor</TenantID>
<AccountingEntityID>200</AccountingEntityID>
<LocationID>
</LocationID>
<ActionCriteria>
<ActionExpression actionCode="Add"/>
</ActionCriteria>
</Sync>
<SalesOrder>--CUT FOR BETTER READABILITY</SalesOrder>
</DataArea>
</SyncSalesOrder>';
DECLARE #COR_OUTBOX_ENTRY TABLE ([C_XML] XML
,[C_TENANT_ID] NVARCHAR(250)
--,[C_MESSAGE_PRIORITY]
,[C_CREATED_DATE_TIME] DATETIME
--,[C_WAS_PROCESSED]
,[C_LOGICAL_ID] NVARCHAR(250));
-- DDL and sample data population, end
;WITH XMLNAMESPACES (DEFAULT 'http://schema.infor.com/InforOAGIS/2')
INSERT INTO #COR_OUTBOX_ENTRY
([C_XML]
,[C_TENANT_ID]
--,[C_MESSAGE_PRIORITY]
,[C_CREATED_DATE_TIME]
--,[C_WAS_PROCESSED]
,[C_LOGICAL_ID])
SELECT #doc AS i_xml
, i_tenant_id = c.value('(DataArea/Sync/TenantID/text())[1]','nvarchar(250)')
--i_message_priority =xdoc.value('()[1]','int'),
, i_created_date_time = c.value('(ApplicationArea/CreationDateTime/text())[1]','datetime')
--i_was_processed = xdoc.value('()[1]','int'),
, i_lid = c.value('(ApplicationArea/Sender/LogicalID/text())[1]','nvarchar(250)')
FROM #doc.nodes('/SyncSalesOrder') AS t(c);
-- test
SELECT * FROM #COR_OUTBOX_ENTRY;

How to get value from a node in XML via SQL Server

I've found several pieces of information online about this but I can't get it working for the life of me.
This is the XML I have:
I need to extract the ID & Name value for each node. There are a lot.
I tried to do this but it returns NULL:
select [xml].value('(/Alter/Object/ObjectDefinition/MeasureGroup/Partitions/Partition/ID)[1]', 'varchar(max)')
from test_xml
I understand the above would return only 1 record. My question is, how do I return all records?
Here's the XML text (stripped down version):
<Alter xmlns="http://schemas.microsoft.com/analysisservices/2003/engine" AllowCreate="true" ObjectExpansion="ExpandFull">
<ObjectDefinition>
<MeasureGroup xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ID>ts_homevideo_sum_20140430_76091ba1-3a51-45bf-a767-f9f3de7eeabe</ID>
<Name>table_1</Name>
<StorageMode valuens="ddl200_200">InMemory</StorageMode>
<ProcessingMode>Regular</ProcessingMode>
<Partitions>
<Partition>
<ID>123</ID>
<Name>2012</Name>
</Partition>
<Partition>
<ID>456</ID>
<Name>2013</Name>
</Partition>
</Partitions>
</MeasureGroup>
</ObjectDefinition>
</Alter>
You need something like this:
DECLARE #MyTable TABLE (ID INT NOT NULL, XmlData XML)
INSERT INTO #MyTable (ID, XmlData)
VALUES (1, '<Alter xmlns="http://schemas.microsoft.com/analysisservices/2003/engine" AllowCreate="true" ObjectExpansion="ExpandFull">
<ObjectDefinition>
<MeasureGroup xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ID>ts_homevideo_sum_20140430_76091ba1-3a51-45bf-a767-f9f3de7eeabe</ID>
<Name>table_1</Name>
<StorageMode valuens="ddl200_200">InMemory</StorageMode>
<ProcessingMode>Regular</ProcessingMode>
<Partitions>
<Partition>
<ID>123</ID>
<Name>2012</Name>
</Partition>
<Partition>
<ID>456</ID>
<Name>2013</Name>
</Partition>
</Partitions>
</MeasureGroup>
</ObjectDefinition>
</Alter>')
;WITH XMLNAMESPACES(DEFAULT 'http://schemas.microsoft.com/analysisservices/2003/engine')
SELECT
tbl.ID,
MeasureGroupID = xc.value('(ID)[1]', 'varchar(200)'),
MeasureGroupName = xc.value('(Name)[1]', 'varchar(200)'),
PartitionID = xp.value('(ID)[1]', 'varchar(200)'),
PartitionName = xp.value('(Name)[1]', 'varchar(200)')
FROM
#MyTable tbl
CROSS APPLY
tbl.XmlData.nodes('/Alter/ObjectDefinition/MeasureGroup') AS XT(XC)
CROSS APPLY
XC.nodes('Partitions/Partition') AS XT2(XP)
WHERE
ID = 1
First of all, you must respect and include the default XML namespace defined in the root of your XML document.
Next, you need to do a nested call to .nodes() to get all <MeasureGroup> and all contained <Partition> nodes, so that you can reach into those XML fragments and extract the ID and Name from them.
This should then result in something like this as output:

How to get value from ntext (in xml format) column in sql

I have a column in my SQL database that is called Triggers_xml_data and its type is ntext. The column is in a xml format and I am trying to get a value from a certain part of the xml. I seen an example of this being done without a column like this:
declare #fileContent xml
set #fileContent ='<my:Header>
<my:Requestor>Mehrlein, Roswitha</my:Requestor>
<my:RequestorUserName>SJM\MehrlR01</my:RequestorUserName>
<my:RequestorEmail>RMehrlein#SJM.com</my:RequestorEmail>
<my:HRContact>Roswita Mehrlein, Beatrice Porta</my:HRContact>
<my:Entity>SJM Germany</my:Entity>
<my:Department>HR/Administration</my:Department>
<my:PositionTitle>Sales Representative</my:PositionTitle>
<my:JobDescription>x0lGQRQAAAABAAAAAAAAAAAeAQAyAAAAVgBAAAAA=</my:JobDescription>
<my:PositionDepartment>Sales</my:PositionDepartment>'
 
;WITH XMLNAMESPACES ('http://schemas.microsoft.com/office/infopath/2003/myXSD/2005-08-29T12-58-51' as my)
select #fileContent.value('(//my:PositionDepartment)[1]', 'varchar(255)')
But I want to select my column like this:
Declare #filevalue xml
select de.triggers_xml_data
from dbo.DEPLOYMENT_ENVIRONMENT as de
But this is not working and I tried to use this #filecontent.value('(//value)[1]','varchar(255)') and making it equal the column value, I have tried casting it but I can't find a way to do this. Is this possible?
When I do this:
SELECT
CAST(
REPLACE(CAST(de.TRIGGERS_XML_DATA AS VARCHAR(MAX)), 'encoding="utf-16"', '')
AS XML).value('(triggers/triggerDefinition/config/item/value)[1]', 'NVARCHAR(max)') as Item, de.ENVIRONMENT_ID
from dbo.DEPLOYMENT_ENVIRONMENT as de
where de.ENVIRONMENT_ID = 19234819
I am getting a null value returned.
Here is an example of what my xml could look like:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<configuration xml:space="preserve">
<triggers>
<defined>true</defined>
<triggerDefinition>
<id>1</id>
<name>After successful deployment</name>
<userDescription/>
<isEnabled>true</isEnabled>
<pluginKey>com.atlassian.bamboo.triggers.atlassian-bamboo-triggers:afterSuccessfulDeployment</pluginKey>
<triggeringRepositories/>
<config>
<item>
<key>deployment.trigger.afterSuccessfulDeployment.triggeringEnvironmentId</key>
<value>19234819</value>
</item>
</config>
</triggerDefinition>
</triggers>
<bambooDelimiterParsingDisabled>true</bambooDelimiterParsingDisabled>
</configuration>
The XML, as you posted it, is not valid. Your code example does not work... It is not allowed to use a namespace prefix without a namespace declaration. Furthermore your example misses the closing Header-tag...
I corrected this...
DECLARE #yourTbl TABLE(ID INT, YourXML NTEXT);
INSERT INTO #yourTbl VALUES
(1,N'<my:Header xmlns:my="DummyUrl">
<my:Requestor>Mehrlein, Roswitha</my:Requestor>
<my:RequestorUserName>SJM\MehrlR01</my:RequestorUserName>
<my:RequestorEmail>RMehrlein#SJM.com</my:RequestorEmail>
<my:HRContact>Roswita Mehrlein, Beatrice Porta</my:HRContact>
<my:Entity>SJM Germany</my:Entity>
<my:Department>HR/Administration</my:Department>
<my:PositionTitle>Sales Representative</my:PositionTitle>
<my:JobDescription>x0lGQRQAAAABAAAAAAAAAAAeAQAyAAAAVgBAAAAA=</my:JobDescription>
<my:PositionDepartment>Sales</my:PositionDepartment>
</my:Header>');
--Lazy approach
SELECT ID
,CAST(CAST(YourXml AS NVARCHAR(MAX)) AS XML).value(N'(//*:PositionDepartment)[1]','nvarchar(max)')
FROM #yourTbl;
--explicit approach
WITH XMLNAMESPACES('DummyUrl' AS my)
SELECT ID
,CAST(CAST(YourXml AS NVARCHAR(MAX)) AS XML).value(N'(/my:Header/my:PositionDepartment)[1]','nvarchar(max)')
FROM #yourTbl
Some Background
If possible you should not store XML in other format than XML and further more one should avoid NTEXT, as it is depricated since SS2005!.
You have to cast NTEXT to NVARCHAR(MAX) first, than cast this to XML. The second will break, if the XML is not valid. That means: If the XML is really the way you posted it, this cannot work!
UPDATE: String-based approach, if XML does not work
If you cannot cast this to XML you might try this
--String based
WITH Casted AS
(
SELECT ID
,CAST(YourXML AS NVARCHAR(MAX)) AS TheXmlAsString
FROM #yourTbl
)
,WithPosition AS
(
SELECT Casted.*
,CHARINDEX(N'<my:PositionDepartment>',TheXmlAsString) + LEN(N'<my:PositionDepartment>') AS FirstLetter
FROM Casted
)
SELECT ID
,SUBSTRING(TheXmlAsString,FirstLetter,CHARINDEX('<',TheXmlAsString,FirstLetter)-FirstLetter)
FROM WithPosition
UPDATE 2
According to your edit the following returns a NULL value. This is good, because it shows, that the cast was successfull.
SELECT
CAST(
REPLACE(CAST(de.TRIGGERS_XML_DATA AS VARCHAR(MAX)), 'encoding="utf-16"', '')
AS XML).value('(triggers/triggerDefinition/config/item/value)[1]',
'NVARCHAR(max)') as Item, de.ENVIRONMENT_ID
from dbo.DEPLOYMENT_ENVIRONMENT as de
where de.ENVIRONMENT_ID = 19234819
Try this (skip namespace with wildcard):
SELECT
CAST(
REPLACE(CAST(de.TRIGGERS_XML_DATA AS VARCHAR(MAX)), 'encoding="utf-16"', '')
AS XML).value('(*:triggers/*:triggerDefinition/*:config/*:item/*:value)[1]', 'NVARCHAR(max)') as Item, de.ENVIRONMENT_ID
from dbo.DEPLOYMENT_ENVIRONMENT as de
where de.ENVIRONMENT_ID = 19234819
And this should be even better:
SELECT
CAST(CAST(de.TRIGGERS_XML_DATA AS NVARCHAR(MAX)) AS XML).value('(*:triggers/*:triggerDefinition/*:config/*:item/*:value)[1]', 'NVARCHAR(max)') as Item, de.ENVIRONMENT_ID
from dbo.DEPLOYMENT_ENVIRONMENT as de
where de.ENVIRONMENT_ID = 19234819
UPDATE 3
I'd rather cut away the full declaration. Your posted example would go like this
DECLARE #DEPLOYMENT_ENVIRONMENT TABLE(ENVIRONMENT_ID INT, TRIGGERS_XML_DATA NTEXT);
INSERT INTO #DEPLOYMENT_ENVIRONMENT VALUES
(19234819,N'<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<configuration xml:space="preserve">
<triggers>
<defined>true</defined>
<triggerDefinition>
<id>1</id>
<name>After successful deployment</name>
<userDescription/>
<isEnabled>true</isEnabled>
<pluginKey>com.atlassian.bamboo.triggers.atlassian-bamboo-triggers:afterSuccessfulDeployment</pluginKey>
<triggeringRepositories/>
<config>
<item>
<key>deployment.trigger.afterSuccessfulDeployment.triggeringEnvironmentId</key>
<value>19234819</value>
</item>
</config>
</triggerDefinition>
</triggers>
<bambooDelimiterParsingDisabled>true</bambooDelimiterParsingDisabled>
</configuration>');
WITH Casted AS
(
SELECT CAST(de.TRIGGERS_XML_DATA AS NVARCHAR(MAX)) AS XmlAsSting
FROM #DEPLOYMENT_ENVIRONMENT as de
where de.ENVIRONMENT_ID = 19234819
)
SELECT CAST(SUBSTRING(XmlAsSting,CHARINDEX('?>',XmlAsSting)+2,8000) AS XML).value('(/*:configuration/*:triggers/*:triggerDefinition/*:config/*:item/*:value)[1]', 'NVARCHAR(max)') as Item
FROM Casted;

adding encoding information to the result of FOR XML [duplicate]

This question already has answers here:
SQL Server FOR XML Enclosing Element?
(2 answers)
Closed 7 years ago.
I have a Script, which returns a XML using FOR XML in SQL 2008. Is there any way to add the version and encoding information in the beginning of the output. Eventually, i am planning to save the output in a file.
For example, right now my output looks like this
<Agents>
<Agent id="1">
<Name>Mike</Name>
<Location>Sanfrancisco</Location>
</Agent>
<Agent id="2">
<Name>John</Name>
<Location>NY</Location>
</Agent>
</Agents>
I would like to append the line <?xml version="1.0" encoding="UTF-8"?> in the beginning of the Xml output
So i want the output something like
<?xml version="1.0" encoding="UTF-8"?>
<Agents>
<Agent id="1">
<Name>Mike</Name>
<Location>Sanfrancisco</Location>
</Agent>
<Agent id="2">
<Name>John</Name>
<Location>NY</Location>
</Agent>
As #gbn points out in another answer and on another question, "the XML data is stored internally as ucs-2", and SQL Server doesn't include it when producing the data. However, you can convert the XML to a string and append the XML declaration at the beginning manually. However, simply using UTF-8 in the declaration would be inaccurate. The Unicode string which SQL produces is in UCS-2. For example, this will fail:
SELECT CONVERT(xml,N'<?xml version="1.0" encoding="UTF-8"?>' + CONVERT(NVARCHAR(MAX),CONVERT(XML,N'<x>' + NCHAR(10176) + N'</x>')));
with error:
Msg 9402, Level 16, State 1, Line 1 XML parsing: line 1, character 38,
unable to switch the encoding
This, on the other hand, will work as expected:
SELECT CONVERT(xml,N'<?xml version="1.0" encoding="UCS-2"?>' + CONVERT(NVARCHAR(MAX),CONVERT(XML,N'<x>' + NCHAR(10176) + N'</x>')));
Here is code which will produce the full, declaration-laden XML string you seek for your example data:
DECLARE #Agents TABLE
(
AgentID int,
AgentName nvarchar(50),
AgentLocation nvarchar(100)
);
INSERT INTO #Agents (AgentID, AgentName, AgentLocation) VALUES (1, N'Mike', N'Sanfrancisco');
INSERT INTO #Agents (AgentID, AgentName, AgentLocation) VALUES (2, N'John', N'NY');
WITH BaseData AS
(
SELECT
(
SELECT
AgentID AS '#id',
AgentName AS 'Name',
AgentLocation AS 'Location'
FROM #Agents
FOR XML PATH('Agent'), ROOT('Agents'), TYPE
) AS AgentXML
), FullStringTable AS
(
SELECT
*,
'<?xml version="1.0" encoding="UCS-2"?>' +
CONVERT(nvarchar(max),AgentXML) AS FullString
FROM BaseData
)
SELECT
AgentXML AS OriginalXML,
FullString,
CONVERT(xml,FullString) AS FullStringConvertedToXML
FROM FullStringTable;
SQL Server internally always uses utf-16 ucs-2 so you could just append it like we did. That is, SQL Server would never generate anything with "utf-8".
Edit: after some digging:
http://www.devnewsgroups.net/group/microsoft.public.sqlserver.xml/topic60022.aspx
http://forums.asp.net/t/1455808.aspx
If you will not be attempting to manipulate the results as TSQL XML then the simplest thing to do will be create a varchar with the string you wish to append then add the XML to it using a CAST statemnt to convert the XML to varchar.
declare #testXML as XML
declare #testPrefix as varchar(255)
set #testPrefix = '<?xml version="1.0" encoding="UTF-8"?>'
set #testXML = '<Agents> <Agent id="1"> <Name>Mike</Name> <Location>Sanfrancisco</Location> </Agent> <Agent id="2"> <Name>John</Name> <Location>NY</Location> </Agent></Agents>'
select #testPrefix
Select #testXML
select #testPrefix + CAST(#testXML as varchar(max))