SQL Server: SELECT XML with Namespaces gives NULL Result - sql

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;

Related

How to add additional XML node on top of my SQL generated XML

I have generated XML from a SQL Server FOR XML PATH statement as shown here:
USE MySQLDB
SELECT *
FROM BillTable
FOR XML PATH ('BillAdd'), ROOT ('BillAddRq')
And this is the result:
<BillAddRq>
<BillAdd>
<TxnID>2432-1071510295</TxnID>
<TimeCreated>2003-12-16T01:44:55</TimeCreated>
<TimeModified>2015-12-15T22:38:33</TimeModified>
<EditSequence>1450190313</EditSequence>
<TxnNumber>413</TxnNumber>
<VendorRef_ListID>E0000-933272656</VendorRef_ListID>
<VendorRef_FullName>Timberloft Lumber</VendorRef_FullName>
<APAccountRef_ListID>C0000-933270541</APAccountRef_ListID>
<APAccountRef_FullName>Accounts Payable</APAccountRef_FullName>
<TxnDate>2016-12-01T00:00:00</TxnDate>
<DueDate>2017-12-31T00:00:00</DueDate>
<AmountDue>80.50000</AmountDue>
<TermsRef_ListID>50000-933272659</TermsRef_ListID>
<TermsRef_FullName>1% 10 Net 30</TermsRef_FullName>
<IsPaid>0</IsPaid>
</BillAdd>
<BillAdd>
<TxnID>243A-1071510389</TxnID>
<TimeCreated>2003-12-16T01:46:29</TimeCreated>
<TimeModified>2015-12-15T22:38:33</TimeModified>
<EditSequence>1450190313</EditSequence>
<TxnNumber>414</TxnNumber>
<VendorRef_ListID>C0000-933272656</VendorRef_ListID>
<VendorRef_FullName>Perry Windows & Doors</VendorRef_FullName>
<APAccountRef_ListID>C0000-933270541</APAccountRef_ListID>
<APAccountRef_FullName>Accounts Payable</APAccountRef_FullName>
<TxnDate>2016-12-02T00:00:00</TxnDate>
<DueDate>2018-01-01T00:00:00</DueDate>
<AmountDue>50.00000</AmountDue>
<TermsRef_ListID>10000-933272658</TermsRef_ListID>
<TermsRef_FullName>Net 30</TermsRef_FullName>
<IsPaid>0</IsPaid>
</BillAdd>
</BillAddRq>
Now, I'd like to encapsulate the above with these nodes:
<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="15.0"?>
<QBXML>
<QBXMLMsgsRq onError="stopOnError">
//above generated xml//
</QBXMLMsgsRq>
</QBXML>
How will I achieve this in a SQL Query I created above?
I am new to SQL Server and XML. I am trying to generate this XML directly from my database and vice versa to make it more efficient and faster — let my SQL directly communicate with XML.
ATTEMPT 1:
USE MySQLDB;
GO
DECLARE #myDoc XML;
SET #myDoc = '<QBXML>
<QBXMLMsgsRq onError="stopOnError">
</QBXMLMsgsRq>
</QBXML>';
SET #myDoc.modify('
insert
-- instead of inserting string here.. I would like to insert here the query I made above
into (/QBXML/QBXMLMsgsRq)[1]');
SELECT #myDoc;
ATTEMPT 2:
USE MySQLDB;
GO
DECLARE #myDoc XML;
SET #myDoc = '<QBXML>
<QBXMLMsgsRq onError="stopOnError">
</QBXMLMsgsRq>
</QBXML>';
DECLARE #qry XML;
SET #qry = (SELECT * FROM BillTable FOR XML PATH ('BillAdd'), ROOT ('BillAddRq'));
-- SELECT #qry;
SET #myDoc.modify('insert #qry
into (/QBXML/QBXMLMsgsRq)[1]');
SELECT #myDoc;
There are many ways to construct your XML result, consider the following three alternatives...
Use XML.modify() to insert the BillTable XML into an XML scalar variable (which includes the ?qbxml XML processing instruction):
declare #BillTableXml xml = (
select *
from BillTable
for xml path('BillAdd'), root('BillAddRq')
);
declare #myDoc xml = '<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="15.0"?>
<QBXML>
<QBXMLMsgsRq onError="stopOnError">
</QBXMLMsgsRq>
</QBXML>';
set #myDoc.modify('
insert sql:variable("#BillTableXml")
into (/QBXML/QBXMLMsgsRq)[1]
');
select #myDoc as Result;
Use a nested query to construct the entire XML result (which does not, however, include the ?qbxml XML processing instruction):
select
'stopOnError' as [QBXML/QBXMLMsgsRq/#onError],
(
select *
from BillTable
for xml path('BillAdd'), root('BillAddRq'), type
) as [QBXML/QBXMLMsgsRq]
for xml path('');
Or use an XQuery to construct the entire XML result (which also includes the ?qbxml XML processing instruction):
select BillTableXml.query('
<?qbxml version="15.0"?>,
<QBXML>
<QBXMLMsgsRq onError="stopOnError">
{ /BillAddRq }
</QBXMLMsgsRq>
</QBXML>
') as Result
from (
select *
from BillTable
for xml path('BillAdd'), root('BillAddRq'), type
) Data (BillTableXml);

How to fetch XML node value with namespace in sql server?

I have to get values of company node elements.I have tried all the
method to fetch data from the node but no luck. Below is my XML.
<?xml version="1.0"?>
<CompanyInvoice xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Customer xmlns="http://t.service/CompanyServices/">
<Company>
<CompanyId>10001</CompanyId>
<CoastalId>454564564564564564564564565465454546565555555</CoastalId>
<CompanyFederalId>345345</CompanyFederalId>
<CompanyName>Anytime Home</CompanyName>
<CompanyAddress>Address1</CompanyAddress>
<CompanyCity>TR</CompanyCity>
<CompanyState>UT</CompanyState>
<CompanyPostalCode>11</CompanyPostalCode>
<CompanyCountry>IT</CompanyCountry>
<CompanyTelephone>(999) 999-9999</CompanyTelephone>
</Company>
<CustomerId>33642</CustomerId>
</Customer>
</CompanyInvoice>
TSQL Code:
I have simply tried with this, but not getting any updates
Declare #DATAXML xml ='<?xml version="1.0"?>
<CompanyInvoice xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Customer xmlns="http://t.service/CompanyServices/">
<Company>
<CompanyId>10001</CompanyId>
<CoastalId>454564564564564564564564565465454546565555555</CoastalId>
<CompanyFederalId>345345</CompanyFederalId>
<CompanyName>Anytime Home</CompanyName>
<CompanyAddress>Address1</CompanyAddress>
<CompanyCity>TR</CompanyCity>
<CompanyState>UT</CompanyState>
<CompanyPostalCode>11</CompanyPostalCode>
<CompanyCountry>IT</CompanyCountry>
<CompanyTelephone>(999) 999-9999</CompanyTelephone>
</Company>
<CustomerId>33642</CustomerId>
</Customer>
</CompanyInvoice>'
;WITH XMLNAMESPACES('http://t.service/CompanyServices/' as x)
Select
a.value('x:CompanyId[1]','nvarchar(50)') as CompanyId,
a.value('x:CoastalId[1]','nvarchar(500)') as CoastalId,
a.value('x:CompanyName[1]','nvarchar(500)') as CompanyName
From #DATAXML.nodes('/CompanyInvoice/Customer/Company')as a (a)
Basically you have two options.
1.Introduce and use namespaces properly. Pay attention to namespaces scope.
2.Use a wildcard namespace (not recommended in production)
Declare #DATAXML xml = N'<?xml version="1.0"?>
<CompanyInvoice xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Customer xmlns="http://t.service/CompanyServices/">
<Company>
<CompanyId>10001</CompanyId>
<CoastalId>454564564564564564564564565465454546565555555</CoastalId>
<CompanyFederalId>345345</CompanyFederalId>
<CompanyName>Anytime Home</CompanyName>
<CompanyAddress>Address1</CompanyAddress>
<CompanyCity>TR</CompanyCity>
<CompanyState>UT</CompanyState>
<CompanyPostalCode>11</CompanyPostalCode>
<CompanyCountry>IT</CompanyCountry>
<CompanyTelephone>(999) 999-9999</CompanyTelephone>
</Company>
<CustomerId>33642</CustomerId>
</Customer>
</CompanyInvoice>';
WITH XMLNAMESPACES('http://t.service/CompanyServices/' as x)
Select
a.value('x:CompanyId[1]','nvarchar(50)') as CompanyId,
a.value('x:CoastalId[1]','nvarchar(500)') as CoastalId,
a.value('x:CompanyName[1]','nvarchar(500)') as CompanyName
From #DATAXML.nodes('CompanyInvoice/x:Customer/x:Company')as a (a);
--
select t.node.value('*:CompanyId[1]', 'int')
from #DATAXML.nodes('*:CompanyInvoice/*:Customer/*:Company') t(node);
Try This this just and other example
REferThis for more info
DECLARE #foo XML
SELECT #foo = N'
<harrys>
<harry>
<fish>0.015000000000</fish>
<bicycle>2008-10-31T00:00:00+01:00</bicycle>
<foo>ü</foo>
</harry>
<harry>
<fish>0.025000000000</fish>
<bicycle>2008-08-31T00:00:00+01:00</bicycle>
<foo>ä</foo>
</harry>
</harrys>
'
SELECT
CAST(CAST(y.item.query('data(fish)') AS varchar(30)) AS float),
CAST(LEFT(CAST(y.item.query('data(bicycle)') AS char(25)), 10) AS smalldatetime),
CAST(y.item.query('data(foo)') AS varchar(25))
FROM
#foo.nodes('/*') x(item)
CROSS APPLY
x.item.nodes('./*') AS y(item)
SELECT
CAST(CAST(x.item.query('data(fish)') AS varchar(30)) AS float),
CAST(LEFT(CAST(x.item.query('data(bicycle)') AS char(25)), 10) AS smalldatetime),
CAST(x.item.query('data(foo)') AS varchar(25))
FROM
#foo.nodes('harrys/harry') x(item)
SELECT
CAST(CAST(y.item.query('data(fish)') AS varchar(30)) AS float),
CAST(LEFT(CAST(y.item.query('data(bicycle)') AS char(25)), 10) AS smalldatetime),
CAST(y.item.query('data(foo)') AS varchar(25))
FROM
#foo.nodes('/harrys') x(item)
CROSS APPLY
x.item.nodes('./harry') AS y(item)
If this dosent work then
Alternate Link

How do you read an XML file in SQL?

I am using SQL Server 2014 to query XML text using xquery. I am able to insert portions of XML text to query but I need to be able to point to a local file to read and query it and cannot figure out how to do that. Below is what I have for what I am currently doing.
declare #xmldata xml
set #xmldata = '
<Orders>
<Order OrderID="100" OrderDate="1/30/2012">
<OrderDetail ProductID="1" Quantity="3">
<Price>350</Price>
</OrderDetail>
<OrderDetail ProductID="2" Quantity="8">
<Price>500</Price>
</OrderDetail>
<OrderDetail ProductID="3" Quantity="10">
<Price>700</Price>
</OrderDetail>
</Order>
<Order OrderID="200" OrderDate="2/15/2012">
<OrderDetail ProductID="4" Quantity="5">
<Price>120</Price>
</OrderDetail>
</Order>
</Orders>'
SELECT x.c.value('(OrderDetail)[2]', 'varchar(100)') as OrderDetail
FROM #xmldata.nodes('/Orders/Order') x(c)
--XMl File Location: "C:\Users\User\X\Example.xml")
Thanks in advance!
Try this https://msdn.microsoft.com/en-CA/library/ms191184.aspx
INSERT INTO T(XmlCol)
SELECT * FROM OPENROWSET(
BULK 'c:\SampleFolder\SampleData3.txt',
SINGLE_BLOB) AS x;

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

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:

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))