防止将XML空标签解析为零

时间:2019-05-17 06:04:50

标签: sql sql-server xml xml-parsing sqlxml

我有一个带有空标记的XML参数。

<dietTypes><dietType><dietaryID></dietaryID></dietType></dietTypes>

我正在尝试在存储过程中将其解析为这样的整数,

DECLARE @MemDietTypes TABLE(DietaryID INT);
INSERT INTO @MemDietTypes
SELECT  DietTypes.Col.value('dietaryID[1]', 'INT')
FROM   @DietaryTypeXML.nodes('//dietType') DietTypes(Col);

以上内容被解析为零,这对我来说是个问题。如何防止这种情况发生?谢谢

3 个答案:

答案 0 :(得分:2)

尝试此操作以了解隐式默认值:

SELECT CAST(NULL AS INT)
      ,CAST('' AS INT)
      ,CAST('      ' AS INT); 

NULL保持不变,但是 empty 默认为零。这就是设计的行为。

现在回到您的问题:

DECLARE @DietaryTypeXML XML='<dietTypes>
                               <dietType>
                                 <dietaryID></dietaryID> <!-- This is empty -->
                               </dietType>
                             </dietTypes>';

-引擎获取一个空值并将其默认为零。
-如果改用varchar,则会出现空白,但必须处理字符串型数字。

SELECT  DietTypes.Col.value('dietaryID[1]', 'INT') AS Empty_in_INT_is_implicitly_taken_as_zero
       ,DietTypes.Col.value('dietaryID[1]', 'VARCHAR(100)') AS Empty_in_VARCHAR_is_implicitly_taken_as_empty_string
FROM   @DietaryTypeXML.nodes('//dietType') DietTypes(Col);

-我建议的解决方案:

SELECT  DietTypes.Col.value('dietaryID[1] cast as xs:int?', 'INT') 
FROM   @DietaryTypeXML.nodes('//dietType') DietTypes(Col);

使用XQuery cast as xs:int?告诉引擎,给定值是可为null的int。现在返回的值不再是 empty ,而是 NULL

答案 1 :(得分:1)

您可以使用text()函数:

declare @data xml = '
    <dietTypes><dietType><dietaryID></dietaryID></dietType><dietType><dietaryID>2</dietaryID></dietType></dietTypes>';

select
    t.c.value('(dietaryID/text())[1]', 'int')
from @data.nodes('//dietType') as t(c);

返回:

dietaryID
-----------
NULL
2

答案 2 :(得分:0)

enter image description here,您需要将DietaryID的数据类型更改为varchar()

declare @xml xml='<dietTypes>
<dietType>
<dietaryID></dietaryID>
</dietType>
</dietTypes>'

DECLARE @MemDietTypes TABLE(DietaryID varchar(10));
INSERT INTO @MemDietTypes
SELECT  DietTypes.Col.value('dietaryID[1]', 'VARCHAR(10)')
FROM   @xml.nodes('//dietTypes/dietType') DietTypes(Col);

select * from @MemDietTypes