T-SQL to produce XML - sql-server

We have a table with the column structure of:
MainPhoneTypeCode
MainPhoneNumber
AlternateNumberTypeCode
AlternatePhoneNumber
And require to output the follow XML:
<ns0:PhoneNumberList>
<ns0:PhoneNumber Type="0096">
<ns0:Number>(08) 8232 5550</ns0:Number>
</ns0:PhoneNumber>
<ns0:PhoneNumber Type="0026">
<ns0:Number>(08) 8336 1050</ns0:Number>
</ns0:PhoneNumber>
</ns0:PhoneNumberList>
For the main phone so far I have:
WITH xmlnamespaces ('http://www.sifassociation.org/datamodel/au/3.4' AS ns0)
SELECT si.MainPhoneTypeCode AS [#Type]
,si.MainPhoneNumber AS [ns0:Number]
FROM EDU.tbl_EDU_SchoolInfo si
WHERE si.SchoolInfoID = 4
FOR XML PATH('ns0:PhoneNumber'), TYPE, ROOT('ns0:PhoneNumberList')
Which generates:
<ns0:PhoneNumberList xmlns:ns0="http://www.sifassociation.org/datamodel/au/3.4">
<ns0:PhoneNumber Type="0096">
<ns0:Number>(08) 8232 5550</ns0:Number>
</ns0:PhoneNumber>
</ns0:PhoneNumberList>
But unsure how to add the alternative number to be included in the PhoneNumberList element.

There is a need for a namespace declaration because all XML tags have a namespace prefix in them.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE
(
SchoolInfoID INT PRIMARY KEY
, MainPhoneTypeCode CHAR(4)
, MainPhoneNumber VARCHAR(20)
, AlternateNumberTypeCode CHAR(4)
, AlternatePhoneNumber VARCHAR(20)
);
INSERT INTO #tbl (
SchoolInfoID,
MainPhoneTypeCode,
MainPhoneNumber,
AlternateNumberTypeCode,
AlternatePhoneNumber
)
VALUES
(4, '0096', '(08) 8232 5550', '0026', '(08) 8336 1050');
-- DDL and sample data population, end
;WITH XMLNAMESPACES ('http://www.sifassociation.org/datamodel/au/3.4' AS ns0)
SELECT MainPhoneTypeCode AS [ns0:PhoneNumber/#Type]
, MainPhoneNumber AS [ns0:PhoneNumber/ns0:Number]
, ''
, AlternateNumberTypeCode AS [ns0:PhoneNumber/#Type]
, AlternatePhoneNumber AS [ns0:PhoneNumber/ns0:Number]
FROM #tbl
WHERE SchoolInfoID = 4
FOR XML PATH(''), TYPE, ROOT('ns0:PhoneNumberList');
Output
<ns0:PhoneNumberList xmlns:ns0="http://www.sifassociation.org/datamodel/au/3.4">
<ns0:PhoneNumber Type="0096">
<ns0:Number>(08) 8232 5550</ns0:Number>
</ns0:PhoneNumber>
<ns0:PhoneNumber Type="0026">
<ns0:Number>(08) 8336 1050</ns0:Number>
</ns0:PhoneNumber>
</ns0:PhoneNumberList>

Related

XML output in SQL help needed

Hi I have the following code in SQL that outputs xml between 2 tables. The output is 90% correct but if possible add to the output and then also remove some of the output text.
I am not sure if SQL has the ability to code a type of a element in the output. Please see the code below with the output. Currently if possible I would like to make 2 changes to my current output. The changes are list at the end of the port
DECLARE #ID_Rechnung int = 1978,
#XMLData xml;
WITH XMLNAMESPACES ('?xml version="1.0" encoding="UTF-8"?' as ext)
SELECT
#XMLData = xmldat.xmldataCol
FROM
(
SELECT (
SELECT
-- HIER XML Daten generieren
[InvoiceHeader].[InvoiceDate] AS 'invoice-date',
([InvoiceHeader].[InvoiceNumber]) AS 'invoice-number',
cast(replace([InvoiceHeader].[GrossValue],' ','') as decimal(18,2)) AS 'gross-total',
cast(replace([InvoiceHeader].[NetValue],' ','') as decimal(18,2)) AS 'amount-due',
[InvoiceHeader].[VatRate] AS 'tax-rate',
cast(replace([InvoiceHeader].[VatValue],' ','') as decimal(18,2)) AS 'tax-amount',
[ImagePath] AS 'image-scan-url',
[InvoiceType] AS 'document-type',
[LegalEntityVATNo] AS 'account-type/id',
[LegalEntityName] AS 'account-type/name',
[SupplierCode] as 'supplier/number',
[Currency] as 'currency/code',
(
SELECT rtrim([InvoiceLines].[LineNumber]) AS [order-line-num]
, [PONumber] as [po-number],
CAST([InvoiceLines].[UnitPrice] AS decimal(18,2)) AS Price ,
[Quantity] as quantity,
[TaxAmount] as [tax-amount],
[LineTotal] as [total],
[Decsription] as description
FROM [InvoiceLines] WHERE [InvoiceLines].[DOCID] = #id_Rechnung
FOR XML PATH('Invoice-line'), ROOT('invoice-lines'), TYPE
)
FROM [InvoiceHeader]
WHERE [InvoiceHeader].[DOCID] = #ID_Rechnung
FOR XML PATH(''), TYPE, ROOT('invoice-header')
) AS xmldataCol
) AS xmldat;
SELECT #XMLData
.query('<invoice-header>
{
for $x in /invoice-header/*[local-name()!="root"]
return $x,
for $x in /invoice-header/root/r
return <invoice-lines>/<invoice-line>{$x/*}</invoice-line></invoice-lines>
}
</invoice-header>');
Output:
<invoice-header>
<invoice-date>20180509</invoice-date>
<invoice-number>1075440</invoice-number>
<gross-total>1376.67</gross-total>
<amount-due>1197.10</amount-due>
<tax-rate>15.00%</tax-rate>
<tax-amount>179.57</tax-amount>
<image-scan-url>\\INTEL-SQL01\Attachment\2018-06-20\7e0dd165-81d6-445a-95d1-8aac686d44ed\f9a1179c-2a54-480e-b97a-ce6ac7327ae0.000</image-scan-url>
<account-type>
<id>4010112052</id>
<name>CONSOLIDATEDPOWERPROJECTS</name>
</account-type>
<supplier>
<number>12345</number>
</supplier>
<currency>
<code>ZAR</code>
</currency>
<invoice-lines xmlns:ext="?xml version="1.0" encoding="UTF-8"?">
<Invoice-line>
<order-line-num>4</order-line-num>
<po-number>120934861</po-number>
<Price>50.00</Price>
<quantity>1.000000</quantity>
<tax-amount>7.500000</tax-amount>
<total>50.00</total>
<description>Test1</description>
</Invoice-line>
<Invoice-line>
<order-line-num>2</order-line-num>
<po-number>120934861</po-number>
<Price>10.00</Price>
<quantity>2.000000</quantity>
<tax-amount>4.500000</tax-amount>
<total>20.00</total>
<description>Test2</description>
</Invoice-line>
</invoice-lines>
</invoice-header>
1.How do I get rid of the following xmlns:ext="?xml version="1.0" encoding="UTF-8&in the line: "<invoice-lines xmlns:ext="?xml version="1.0" encoding="UTF-8"?">"
How would I code "<tax-amount>7.500000</tax-amount> to get the output": "<tax-amount type="decimal">7.500000</tax-amount>"
Without a minimal reproducible example it is not possible to give you a full working answer.
(1) As #JeroenMostert already pointed out, the
'?xml version="1.0" encoding="UTF-8"?'
is an XML prolog declaration. Just delete the following line:
WITH XMLNAMESPACES ('?xml version="1.0" encoding="UTF-8"?' as ext)
(2) Here is a conceptual example how to add an attribute to an XML element. What is important here is a sequential order of adding, i.e. attribute shall be first, element itself is 2nd.
SQL
DECLARE #tbl TABLE (ID INT IDENTITY PRIMARY KEY, [tax-amount] VARCHAR(20));
INSERT INTO #tbl ([tax-amount]) VALUES
(N'7.500000'),
(N'18.000000');
SELECT
'decimal' AS [tax-amount/#type]
, [tax-amount]
FROM #tbl
FOR XML PATH('r'), TYPE, ROOT('root');
Output
<root>
<r>
<tax-amount type="decimal">7.500000</tax-amount>
</r>
<r>
<tax-amount type="decimal">18.000000</tax-amount>
</r>
</root>

CDATA with Child elements

I would like the outcome with a subset of the MakeType .
Right now I get the entire block and not elements of the MakeType.
When the XML resolves the Type, the Series and class tag an element for those should be created. This is on SQL Server Standard 2017.And I really don't know CDATA xml style and would not use it but the vendor requires the CDATA type.
---Create Temp Table
declare #RepCar table
(
[Name] varchar(10),
[Make] varchar(10),
[Model] varchar(10),
[Price] money,
[Type] varchar(10),
[Series] varchar(10),
[Class] Varchar(10)
);
insert into #RepCar
(
Name, Make, Model, Price, Type, Series, Class
)
values
('Car1', 'Make1', 'Model1', 100, 'Type1', 'IS', 'Sedan'),
('Car1', 'Make1', 'Model1', 100, 'Type1', 'LS' , 'Sport'),
('Car2', 'Make2', 'Model2', 200, 'Type2', 'M3' , 'Sport'),
('Car3', 'Make3', 'Model3', 300, 'Type3','GS350','Sedan');
--Declare Variables
DECLARE #TransactionId NVARCHAR(100)
DECLARE #TransactionDateTime DATETIME
--Setting Variable
SET #TransactionId= (SELECT CONVERT(VARCHAR, CURRENT_TRANSACTION_ID()))
SET #TransactionDateTime= GETDATE()
--Create the XML
select 1 AS Tag,
0 AS Parent,
'CollectSamplingData' as 'Message!1!TransactionType!cdata',
#TransactionId as 'Message!1!TransactionID!cdata',
#TransactionDateTime as 'Message!1!TransactionDate!cdata',
[Name] as 'Message!1!CName!cdata',
[Make] as 'Message!1!MakeCar!cdata',
[Model] as 'Message!1!MakeModel!cdata',
[Price] as 'Message!1!DataValue!cdata',
[Type] as 'Message!1!MakeType!cdata' ,
-----This is the SQL that is'nt working.
( select
1 AS Tag,
0 AS Parent,
[Series] as 'Message!2!MakeSeries!cdata',
[Class] as 'Message!2!MakeClass!cdata'
from #RepCar
FOR XML EXPLICIT
)
from #RepCar
FOR XML EXPLICIT, ROOT('Message');
The Outcome should look like this.When the code does see a the MakeType should have the Series and class below as the child element. These are the desired output XML
<Message>
<Message>
<TransactionType><![CDATA[CollectSamplingData]]></TransactionType>
<TransactionID><![CDATA[1482282230]]></TransactionID>
<TransactionDate><![CDATA[2020-02-03T11:05:17.340]]></TransactionDate>
<CName><![CDATA[Car1]]></CName>
<MakeCar><![CDATA[Make1]]></MakeCar>
<MakeModel><![CDATA[Model1]]></MakeModel>
<DataValue><![CDATA[100.0000]]></DataValue>
<MakeType><![CDATA[Type1]]>
<Series><![CDATA[IS]></Series>
<Class><![CDATA[Sedan]]></Class>
<Series><![CDATA[LS]></Series>
<Class><![CDATA[Sport]]></Class>
<Series><![CDATA[M3]></Series>
<Class><![CDATA[Sport]]></Class>
<Series><![CDATA[GS350]></Series>
<Class><![CDATA[Sedan]]></Class>>
</MakeType>
</Message>
I struggled to produce what you need by using FOR XML EXPLICIT. Eventually, I reverted to using XQuery FLWOR expression. Please remember that SQL Server XML data type cannot hold CDATA sections. You need to use the NVARCHAR(MAX) data type. Check it out here: How to use CDATA in SQL XML
SQL
-- DDL and sample data population, start
DECLARE #RepCar TABLE
(
[Name] VARCHAR(10),
[Make] VARCHAR(10),
[Model] VARCHAR(10),
[Price] MONEY,
[Type] VARCHAR(10),
[Series] VARCHAR(10),
[Class] VARCHAR(10)
);
INSERT INTO #RepCar
(
Name,
Make,
Model,
Price,
Type,
Series,
Class
)
VALUES
('Car1', 'Make1', 'Model1', 100, 'Type1', 'IS', 'Sedan'),
('Car1', 'Make1', 'Model1', 100, 'Type1', 'LS', 'Sport'),
('Car2', 'Make2', 'Model2', 200, 'Type2', 'M3', 'Sport'),
('Car3', 'Make3', 'Model3', 300, 'Type3', 'GS350', 'Sedan');
-- DDL and sample data population, end
--Declare Variables
DECLARE #TransactionId NVARCHAR(100) = CURRENT_TRANSACTION_ID();
DECLARE #TransactionDateTime DATETIME = GETDATE();
DECLARE #lt NCHAR(4) = '<'
, #gt NCHAR(4) = '>';
SELECT REPLACE(REPLACE(TRY_CAST((SELECT 'CollectSamplingData' AS [TransactionType]
, #TransactionId AS [TransactionID]
, #TransactionDateTime AS [TransactionDate]
, *
FROM #RepCar
FOR XML PATH('r'), TYPE, ROOT('root')).query('<Messages><Message>
{
for $x in /root/r[1]
return (<TransactionType>{concat("<![CDATA[", data($x/TransactionType[1]), "]]>")}</TransactionType>,
<TransactionID>{concat("<![CDATA[", data($x/TransactionID[1]), "]]>")}</TransactionID>,
<TransactionDate>{concat("<![CDATA[", data($x/TransactionDate[1]), "]]>")}</TransactionDate>,
<CName>{concat("<![CDATA[", data($x/Name[1]), "]]>")}</CName>,
<MakeCar>{concat("<![CDATA[", data($x/Make[1]), "]]>")}</MakeCar>,
<MakeModel>{concat("<![CDATA[", data($x/Model[1]), "]]>")}</MakeModel>,
<DataValue>{concat("<![CDATA[", data($x/Price[1]), "]]>")}</DataValue>,
<MakeType>{concat("<![CDATA[", data($x/Type[1]), "]]>")}
{
for $y in /root/r
return (
<Series>{concat("<![CDATA[", data($y/Series[1]), "]]>")}</Series>,
<Class>{concat("<![CDATA[", data($y/Class[1]), "]]>")}</Class>
)
}
</MakeType>)
}
</Message></Messages>') AS NVARCHAR(MAX)), #lt,'<'), #gt, '>') AS [XML with CDATA sections];
Output
<Messages>
<Message>
<TransactionType><![CDATA[CollectSamplingData]]></TransactionType>
<TransactionID><![CDATA[1149709]]></TransactionID>
<TransactionDate><![CDATA[2020-02-03T16:23:43.020]]></TransactionDate>
<CName><![CDATA[Car1]]></CName>
<MakeCar><![CDATA[Make1]]></MakeCar>
<MakeModel><![CDATA[Model1]]></MakeModel>
<DataValue><![CDATA[100.0000]]></DataValue>
<MakeType><![CDATA[Type1]]>
<Series><![CDATA[IS]]></Series>
<Class><![CDATA[Sedan]]></Class>
<Series><![CDATA[LS]]></Series>
<Class><![CDATA[Sport]]></Class>
<Series><![CDATA[M3]]></Series>
<Class><![CDATA[Sport]]></Class>
<Series><![CDATA[GS350]]></Series>
<Class><![CDATA[Sedan]]></Class>
</MakeType>
</Message>
</Messages>
Just for comparison, I would like to show how easy to implement CDATA section when the XQuery engine fully supports standards. Below is BaseX 9.3.1 implementation which is using cdata-section-elements serialization parameter: List of elements to be output as CDATA, separated by whitespaces.
Two elements <city> and <motto> are emitted as CDATA section in a simple declarative way.
XQuery
xquery version "3.1";
declare option output:omit-xml-declaration "no";
declare option output:cdata-section-elements "city motto";
declare context item := document {
<root>
<row>
<state>FL</state>
<motto>In God We Trust</motto>
<city>Miami</city>
</row>
<row>
<state>NJ</state>
<motto>Liberty and Prosperity</motto>
<city>Trenton</city>
</row>
</root>
};
<root>
{
for $r in ./root/row
return $r
}
</root>
Output
<?xml version="1.0" encoding="UTF-8"?>
<root>
<row>
<state>FL</state>
<motto><![CDATA[In God We Trust]]></motto>
<city><![CDATA[Miami]]></city>
</row>
<row>
<state>NJ</state>
<motto><![CDATA[Liberty and Prosperity]]></motto>
<city><![CDATA[Trenton]]></city>
</row>
</root>

Manipulate XMLNamespaces

I have the following output from SQL using FOR XML clause:
<q17:DestinationSection xmlns:q17="http://ITrack.Transmission/2011/02/25/Objects">
<q17:DestinationCode>1</q17:DestinationCode>
<q17:DestinationName>Strada Rampei 9, Iasi</q17:DestinationName>
<q17:DestinationAddress1>Strada Rampei 9, Iasi</q17:DestinationAddress1>
<q17:DestinationAddress2>
xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
</q17:DestinationAddress2>
</q17:DestinationSection>
The DestinationSection is the main root for this block of data. Is there any possibility to do some workaround and to have something like below in the <q17:DestinationAddress2></q17:DestinationAddress2> tag?
<q17:DestinationAddress2 xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"</q17:DestinationAddress2>
I have tried something but I get an error that says that I need to declare the namespace but I really don't know where to "introduce" that definition.
My SQL statement
DECLARE #XMLFINAL VARCHAR(MAX)
SET #XMLFINAL=''
DECLARE #XMLFINAL2 VARCHAR(MAX)
SET #XMLFINAL2=''
DECLARE #NUMBER NVARCHAR(100)
DECLARE #NUMBER2 NVARCHAR(100)
DECLARE #XML VARCHAR(MAX)
DECLARE #XML2 VARCHAR(MAX)
DECLARE Rec CURSOR FAST_FORWARD FOR
SELECT GID FROM PurchaseDocumentsHeader
OPEN Rec
FETCH NEXT FROM Rec INTO #NUMBER2
WHILE ##FETCH_STATUS = 0
BEGIN
SET #XML2=''
;WITH XMLNAMESPACES ('http://ITrack.Transmission/2011/02/25/Objects' as q17)
SELECT #XML2= (
SELECT
DestCode AS 'q17:DestinationCode', DestDescr 'q17:DestinationName', DestAddr AS 'q17:DestinationAddress1', DestAddr2 AS 'q17:DestinationAddress2',
DestZIP AS 'q17:DestinationZIP'
FROM PurchaseDocumentsHeader WHERE GID=#NUMBER2
FOR XML RAW('q17:DestinationSection'),ELEMENTS
)
FETCH NEXT FROM Rec INTO #NUMBER2
SET #XMLFINAL2=#XMLFINAL2+#XML2
END
CLOSE Rec DEALLOCATE Rec
EDIT
Please find below my DDL. It's a view used to extract the data from an official table.
CREATE VIEW [dbo].[PurchaseDocumentsHeader]
AS
SELECT esd.GID, esd.ADRegistrationDate, esgo.Code AS DestCode, esgo.Description AS DestDescr, esgo.Address1 AS DestAddr, esgo.fCityCode AS DestCity,
esgp.TaxRegistrationNumber AS DestZIP, 'xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' AS DestAddr2, esgo.Description AS DestRomanized,
esgo.Address1 AS DestAddress1Romanized,
'xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' AS DestAddress2Romanized, esgp.TaxRegistrationNumber AS DestZIPRom,
esgo.fCityCode AS DestCityRomanized, esgo.fCountryCode AS DestCountry, cast('DestinationGLN xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>' AS XML) AS DestGLN,
'xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' AS DestCoord
FROM ESFIDocumentTrade esd
LEFT JOIN ESGOSites esgo on esd.fDeliverySiteGID=esgo.GID
LEFT JOIN ESFITradeAccount esc on esd.fTradeAccountGID=esc.GID
LEFT JOIN ESGOPerson esgp on esc.fPersonCodeGID=esgo.GID
LEFT JOIN ESFIDocumentType est on esd.fADDocumentTypeGID=est.GID
WHERE esd.fTransitionStepCode='APPROVED' AND est.Code='CVR'
AND YEAR(esd.ADRegistrationDate)=YEAR(GETDATE())
AND MONTH(esd.ADRegistrationDate)=MONTH(GETDATE())
AND DAY(esd.ADRegistrationDate)=DAY(GETDATE())
GO
Later edit
CREATE TABLE DocPurcharseHeader
(
ADRegistrationDate date,
Code NVARCHAR(4000),
Description NVARCHAR(4000),
Address1 NVARCHAR (4000),
Address2 NVARCHAR (4000),
City NVARCHAR (4000),
ZIPCode NVARCHAR(4000)
)
INSERT INTO DocPurcharseHeader (ADRegistrationDate, Code, Description, Address1, Address2, City, ZIPCode)
VALUES('2017-10-16', '01', 'MyPOS', 'MyPOSAddress1', 'MyPOSAddress2', 'BUCHAREST', '123456')
2nd Later edit
;WITH XMLNAMESPACES ('http://ITrack.Transmission/2011/02/25/Objects' as q17)
SELECT #XMLSalesOrders=(
SELECT DestCode AS [q17:DestinationCode]
,DestDescr AS [q17:DestinationName]
,DestAddr AS [q17:DestinationAddress1]
,DestAddr2 AS [q17:DestinationAddress2]
FROM PurchaseDocumentsHeader
FOR XML PATH('q17:DestinationSection'),ELEMENTS XSINIL,ROOT('q17:DestinationSections'))
This code above is generating the below output, without XSINL directive:
<q17:DestinationSections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q17="http://ITrack.Transmission/2011/02/25/Objects">
<q17:DestinationSection>
<q17:DestinationCode>1</q17:DestinationCode>
<q17:DestinationName>Strada Rampei 9, Iasi</q17:DestinationName>
<q17:DestinationAddress1>Strada Rampei 9, Iasi</q17:DestinationAddress1>
<q17:DestinationAddress2/>
</q17:DestinationSection>
<q17:DestinationSection>
you are trying to out-trick the very mighty XML engine.
As stated in your other question:
Never do this in a CURSOR! They are bad and evil, coming directly of the hell of procedural thinking and were invented by the devil of spaghetti code...
Try it like this:
I use your table DDL an insert some data. The second row will have a NULL in address2. Normally XML will simply omit NULL values. A not existing node is read as a NULL value. But you can force NULLs to be introduced as xsi.nil="true" with ELEMENTS XSINIL:
CREATE TABLE DocPurcharseHeader
(
ADRegistrationDate date,
Code NVARCHAR(4000),
Description NVARCHAR(4000),
Address1 NVARCHAR (4000),
Address2 NVARCHAR (4000),
City NVARCHAR (4000),
ZIPCode NVARCHAR(4000)
);
INSERT INTO DocPurcharseHeader (ADRegistrationDate, Code, Description, Address1, Address2, City, ZIPCode)
VALUES('2017-10-16', '01', 'MyPOS', 'MyPOSAddress1', 'MyPOSAddress2', 'BUCHAREST', '123456')
,('2017-10-16', '01', 'MyPOS', 'MyPOSAddress1', NULL, 'BUCHAREST', '123456');
WITH XMLNAMESPACES('http://ITrack.Transmission/2011/02/25/Objects' AS q17)
SELECT Code AS [q17:DestinationCode]
,Description AS [q17:DestinationName]
,Address1 AS [q17:DestinationAddress1]
,Address2 AS [q17:DestinationAddress2]
FROM DocPurcharseHeader
FOR XML PATH('q17:DestinationSection'),ELEMENTS XSINIL,ROOT('q17:DestinationSections');
The result
<q17:DestinationSections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q17="http://ITrack.Transmission/2011/02/25/Objects">
<q17:DestinationSection>
<q17:DestinationCode>01</q17:DestinationCode>
<q17:DestinationName>MyPOS</q17:DestinationName>
<q17:DestinationAddress1>MyPOSAddress1</q17:DestinationAddress1>
<q17:DestinationAddress2>MyPOSAddress2</q17:DestinationAddress2>
</q17:DestinationSection>
<q17:DestinationSection>
<q17:DestinationCode>01</q17:DestinationCode>
<q17:DestinationName>MyPOS</q17:DestinationName>
<q17:DestinationAddress1>MyPOSAddress1</q17:DestinationAddress1>
<q17:DestinationAddress2 xsi:nil="true" />
</q17:DestinationSection>
</q17:DestinationSections>
UPDATE: About NULL values:
Try this
DECLARE #DummyTable TABLE(SomeDescription VARCHAR(500), SomeValue VARCHAR(100));
INSERT INTO #DummyTable VALUES('A real NULL value',NULL)
,('An empty string','')
,('A blank string',' ')
,('Some Text','blah blah');
WITH XMLNAMESPACES('SomeURL' AS q17)
SELECT SomeDescription AS [q17:Description]
,SomeValue AS [q17:Value]
FROM #DummyTable
FOR XML PATH('q17:row'),ELEMENTS XSINIL,ROOT('root');
To get this
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q17="SomeURL">
<q17:row>
<q17:Description>A real NULL value</q17:Description>
<q17:Value xsi:nil="true" />
</q17:row>
<q17:row>
<q17:Description>An empty string</q17:Description>
<q17:Value></q17:Value>
</q17:row>
<q17:row>
<q17:Description>A blank string</q17:Description>
<q17:Value> </q17:Value>
</q17:row>
<q17:row>
<q17:Description>Some Text</q17:Description>
<q17:Value>blah blah</q17:Value>
</q17:row>
</root>
You can see, that the real NULL is encoded as xsi:nil="true", while the empty string is shown as <q17:Value></q17:Value> (which is exactly the same as <q17:Value />).
Check this answer for some examples about NULL and empty. Check this answer to understand more about text()

Using stored procedures to simplify XML generation

I am trying to write an SP to return invoice details in XML for transferring to a third party.
I have a working SP but it's a bit messy (simplified below):
SELECT (
SELECT GETDATE() AS HEADER_SLAStartTime
, DATEADD(HOUR, #SLA_HOURS, GETDATE()) AS HEADER_SLAEndTime
FOR XML PATH ('Header'), TYPE
) , (
SELECT ACCT AS CustomerCode
, ACCTNAME As CustomerName
, ADDR#1 As AddressLine1
, ADDR#2 AS AddressLine2
, ADDR#3 AS AddressLine3
, ADDR#4 AS AddressLine4
, POSTCODE AS AddressPostcode
, TELNO AS AddressTelno
FROM InvHdr
WHERE INVNO = #INVNO
FOR XML PATH('Customer'), TYPE
) , (
SELECT (
SELECT INVNO AS InvoiceNo
, [DATE] AS InvoiceDate
, [INVTYPE] AS InvoiceType
, CASE [SOURCE] WHEN 0 THEN 'Contract' WHEN 1 THEN 'Manual' WHEN 2 THEN 'Sales Order' ELSE '' END AS InvoiceSourceText
, THEIRREF AS CustomerReference
, YOURREF AS InternalReference
, (
SELECT ITEMNO AS ItemCode
, [ITEMDESC#1] AS ItemDesc
, [TYPE] AS ItemType
, [MEMO] AS ItemMemo
, [GOODS] AS ItemCharge
, [DISCOUNT] AS ItemDiscount
FROM InvItems
WHERE INVNO = HDR.INVNO
FOR XML PATH('InvItem'), TYPE
)
FROM InvHdr HDR
WHERE INVNO = #INVNO
FOR XML PATH('InvoiceHeader'), TYPE
) , (
SELECT HDR.[GOODS] AS InvoiceNet
, HDR.VAT AS InvoiceVAT
, HDR.[GOODS] + HDR.VAT AS InvoiceGross
, (
SELECT VATCODE AS VATListCode
, VATAMT AS VATListAmount
, VATDESC AS VATListDescription
, VATRATE AS VATListRate
, VATGOODS AS VATListGoods
FROM InvVAT
WHERE InvVAT.INVNO = HDR.INVNO
ORDER BY VATAMT DESC
FOR XML PATH('VATSummary'), TYPE
)
FROM InvHdr HDR
WHERE INVNO = #INVNO
FOR XML PATH('InvoiceFooter'), TYPE
)
FOR XML PATH('Invoices'), TYPE
)
FOR XML PATH(''), ROOT('Output')
This procedure works but I have to create lots of these to get different bits of information in different orders, I have tried creating separate SP's to get the data in sections, below is my first section SP:
CREATE PROCEDURE UDEF_DC_XML_INVOICEFOOTER(
#INVNO INT
)
AS
BEGIN
SELECT HDR.[GOODS] AS InvoiceNet
, HDR.VAT AS InvoiceVAT
, HDR.[GOODS] + HDR.VAT AS InvoiceGross
, (
SELECT VATCODE AS VATListCode
, VATAMT AS VATListAmount
, VATDESC AS VATListDescription
, VATRATE AS VATListRate
, VATGOODS AS VATListGoods
FROM InvVAT
WHERE InvVAT.INVNO = HDR.INVNO
ORDER BY VATAMT DESC
FOR XML PATH('VATSummary'), TYPE
)
FROM InvHdr HDR
WHERE INVNO = #INVNO
FOR XML PATH('InvoiceFooter'), TYPE
END
When I try calling this:
SELECT UDEF_DC_XML_INVOICEFOOTER(#INVNO)
FOR XML PATH('Invoices'), TYPE
I get the error:
Msg 4121, Level 16, State 1, Line 1
Cannot find either column "dbo" or the user-defined function or aggregate "dbo.UDEF_DC_XML_INVOICEFOOTER", or the name is ambiguous.
In the end I'm hoping to be able to create multiple 4/5 line SP's that will call all the sections in the correct order. Either via calling the individual SP's in order or writing each section to variables and building the full XML afterwards.
Is it possible to call multiple stored procedures returning XML within a single statement?
Is it possible to call multiple stored procedures returning XML within
a single statement?
No, but you can use functions that return XML.
create function dbo.GetXML(#Value int) returns xml
as
begin
return (
select #Value as X
for xml path('Y'), type
)
end
Use like this:
select dbo.GetXML(1)
for xml path('Z')
Result:
<Z>
<Y>
<X>1</X>
</Y>
</Z>

Query XML creating field names whithout knowing node names

If I have a SQL SERVER 2012 table containing an XML field type. The records it could contain are as follows.
I have simplified my problem to the following.
Record 1:
ID_FIELD='nn1'
XML_FIELD=
<KNOWN_NAME_1>
<UNKNOWN_NAME1>Some value</UNKNOWN_NAME1>
<UNKNOWN_NAME2>Some value</UNKNOWN_NAME2>
... Maybe more ...
</KNOWN_NAME_1>
Record 2:
ID_FIELD='nn2'
XML_FIELD=
<KNOWN_NAME_2>
<UNKNOWN_NAME1>Some value</UNKNOWN_NAME1>
<UNKNOWN_NAME2>Some value</UNKNOWN_NAME2>
... Maybe more unknown fields ...
</KNOWN_NAME_2>
I want to output non xml:
UNKNOWN_NAME1 | UNKNOWN_NAME2 | ETC
-----------------------------------
Some Value Some value
For a known root value (i.e. KNOWN_NAME_1)
I.e. If I new the node values (which I don't) I could
SELECT
XMLData.Node.value('UNKNOWN_NAME1[1]', 'varchar(100)') ,
XMLData.Node.value('UNKNOWN_NAME2[1], 'varchar(100)')
FROM FooTable
CROSS APPLY MyXmlField.nodes('//KNOWN_NAME_1') XMLData(Node)
-- WHERE SOME ID value = 'NN1' (all XML records have a separate id)
All is good however I want to do this for all the nodes (unknown quantity) without knowing the node names. The root will only contain nodes it wont get any deeper.
Is this possible in SQL?
I have looked at this but I doubt I can get enough rights to implement it.
http://architectshack.com/ClrXmlShredder.ashx
If you don't know the column names in the output you have to use dynamic SQL:
-- Source table
declare #FooTable table
(
ID_FIELD char(3),
XML_FIELD xml
)
-- Sample data
insert into #FooTable values
('nn1', '<KNOWN_NAME_1>
<UNKNOWN_NAME1>Some value1</UNKNOWN_NAME1>
<UNKNOWN_NAME2>Some value2</UNKNOWN_NAME2>
</KNOWN_NAME_1>')
-- ID to look for
declare #ID char(3) = 'nn1'
-- Element name to look for
declare #KnownName varchar(100) = 'KNOWN_NAME_1'
-- Variable to hold the XML to process
declare #XML xml
-- Get the XML
select #XML = XML_FIELD
from #FooTable
where ID_FIELD = #ID
-- Variable for dynamic SQL
declare #SQL nvarchar(max)
-- Build the query
select #SQL = 'select '+stuff(
(
select ',T.N.value('''+T.N.value('local-name(.)', 'sysname')+'[1]'', ''varchar(max)'') as '+T.N.value('local-name(.)', 'sysname')
from #XML.nodes('/*[local-name(.)=sql:variable("#KnownName")]/*') as T(N)
for xml path(''), type
).value('.', 'nvarchar(max)'), 1, 1, '')+
' from #XML.nodes(''/*[local-name(.)=sql:variable("#KnownName")]'') as T(N)'
-- Execute the query
exec sp_executesql #SQL,
N'#XML xml, #KnownName varchar(100)',
#XML = #XML,
#KnownName = #KnownName
Result:
UNKNOWN_NAME1 UNKNOWN_NAME2
--------------- ---------------
Some value1 Some value2
The dynamically generated query looks like this:
select T.N.value('UNKNOWN_NAME1[1]', 'varchar(max)') as UNKNOWN_NAME1,
T.N.value('UNKNOWN_NAME2[1]', 'varchar(max)') as UNKNOWN_NAME2
from #XML.nodes('/*[local-name(.)=sql:variable("#KnownName")]') as T(N)
SE-Data

Resources