简体   繁体   English

SQL-将XML转换为nvarchar(max)

[英]SQL - cast XML as nvarchar(max)

I've got a problem with an SQL stored procedure . 我有一个SQL stored procedure的问题。 I need to generate a xml from a database. 我需要从数据库生成xml In my stored procedure, I collect all information and then my plan was to generate the XML file as I need it (see code). 在存储过程中,我收集了所有信息,然后我的计划是根据需要生成XML文件(请参见代码)。

All transactions I need to report are loaded into the variable @transactionXml . 我需要报告的所有交易都被加载到变量@transactionXml It is of data type xml and can become quite big. 它是xml数据类型,并且可能变得很大。

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. 当我尝试将数据类型转换为nvarchar(max) (如代码部分所示),字符串不完整,并且缺少一些信息。 It seems, that the string is cut after x-signs. 看来,该字符串在x符号后被剪切。

Is there a way to cast the @transactionXml variable completely to text, so that I can use it in my @xmlOut statement? 有没有一种方法可以将@transactionXml变量完全转换为文本,以便可以在我的@xmlOut语句中使用它?

You should not create an XML on string level! 您不应该在字符串级别创建XML! 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. 预先创建的XML必须很好,否则您将无法将其存储为XML本机类型。

Creating the XML on string level can have various dangerous side effects. 在字符串级别创建XML可能会有各种危险的副作用。 Just imagine a forbidden character within one of your variables... 试想一下,您的变量之一中有一个禁止的字符...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM