Home SQL - cast XML as nvarchar(max)
Reply: 1

SQL - cast XML as nvarchar(max)

dns_nx
1#
dns_nx Published in 2018-01-11 15:41:50Z

I've got a problem with an SQL stored procedure. I need to generate a xml from a database. In my stored procedure, I collect all information and then my plan was to generate the XML file as I need it (see code).

All transactions I need to report are loaded into the variable @transactionXml. It is of data type xml and can become quite big.

SET @xmlOut += '<export_datuma>' + cast(CAST(getdate() as date) as nvarchar(100)) + '</export_datuma>'
SET @xmlOut += '<export_szla_db>' + @noOfResults + '</export_szla_db>'
SET @xmlOut += '<kezdo_ido>' + cast(@fromDate as nvarchar(max)) + '</kezdo_ido>'
SET @xmlOut += '<zaro_ido>' + cast(@toDate as nvarchar(max)) + '</zaro_ido>'
SET @xmlOut += '<kezdo_szla_szam>' + @minInvoiceNo + '</kezdo_szla_szam>'
SET @xmlOut += '<zaro_szla_szam>' + @maxInvoiceNo + '</zaro_szla_szam>'
SET @xmlOut += cast(@transactionXml as nvarchar(max))
SET @xmlOut += '</szamlak>'

SELECT @xmlOut

When I try to cast the datatype to nvarchar(max) (as in the code section), the string is not complete and missing some information. It seems, that the string is cut after x-signs.

Is there a way to cast the @transactionXml variable completely to text, so that I can use it in my @xmlOut statement?

Shnugo
2#
Shnugo Reply to 2018-01-11 16:27:07Z

You should not create an XML on string level! Try this:

SELECT CAST(getdate() as date) AS export_datuma
      ,@noOfResults AS export_szla_db
      ,@fromDate AS kezdo_ido
      ,@toDate AS zaro_ido
      ,@minInvoiceNo AS kezdo_szla_szam
      ,@maxInvoiceNo AS zaro_szla_szam
      ,@transactionXml AS [*] --This is the pre-created XML which should be fine
FOR XML PATH('szamlak');

The pre-created XML must be fine, otherwise you could not store it as XML native type.

Creating the XML on string level can have various dangerous side effects. Just imagine a forbidden character within one of your variables...

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.299549 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO