Selecting null value from XML in SQL Server

前端 未结 8 1470
Happy的楠姐
Happy的楠姐 2021-02-19 20:23

I\'m trying to select from XML that has a null as one of the attributes. Instead of returning a null, it returns a 0. What am I doing wrong?
See code below to replicate:

8条回答
  •  名媛妹妹
    2021-02-19 20:42

    Because you are setting the fields to INT you have the problem that both xsi:nil="true" fields and the value 0 will end up as 0 as the default value for INT Is 0.

    You could convert to VARCHAR first to detect the empty string ('') that string fields containing xsi:nil="true" produce and then convert the result to INT.

    This SELECT will give you the answer you are after

    SELECT  CONVERT(INT,NULLIF(ParamValues.TaskChainerTask.query('Property1').value('.', 'varchar(5)'),'')) AS Property1
          , CONVERT(INT,NULLIF(ParamValues.TaskChainerTask.query('Property2').value('.', 'varchar(5)'),'')) AS Property2
    FROM    @a.nodes('(/TestSet/Element)') AS ParamValues (TaskChainerTask) 
    

    The result of this gives you:

    Property1   Property2
    1           1
    NULL        2
    3           3
    

提交回复
热议问题