Selecting null value from XML in SQL Server

前端 未结 8 1491
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条回答
  •  旧时难觅i
    2021-02-19 21:07

    A clever way of doing this would be to remove the Property1 node from the XML where null values are desired. So what ever node you want to be null in your result set just do not add it to the XML. In this way you will not have to add the xsi:nill attribute as well.

    So Below will also result in a null:

    declare @a xml
    select @a = '
      
        1
        1
      
      
         //I have removed the property1 node and this will result in a null value
        2
      
      
        3
        3
      
    '
    
     select ParamValues.TaskChainerTask.value('./Property1[1]','int') as Property1,
            ParamValues.TaskChainerTask.value('./Property2[1]','int') as Property2
       from @a.nodes('(/TestSet/Element)') as ParamValues(TaskChainerTask)
    

    It can be seen in the above example that there is no Property1 node hence it will result in a null value

提交回复
热议问题