SQL select for xml explicit - 当value为null时需要帮助定义替代结构

时间:2012-03-19 07:42:36

标签: sql xml sql-server-2008

我有以下SQL查询,我无法明确定义

的形状
select tableName, uqName, col1, col2
from someTable

我想将结果选择为XML,如下所示。我需要col1和col2显示为children,tableName和uqName显示为属性。如果col1或col2是null,那么我需要指定IsNull属性。否则,该值将被选为文本节点,作为Col元素的子元素

从上面的SQL返回的一行如下所示:

<UniqueKey Name="UniqueKeyName" TableName="TableName" >
  <Col Name="col1" IsNull="true" />
  <Col Name="col2">ABC</Col>
</UniqueKey>

如何使用SQL Server 2008 R2明确定义此XML形状?

1 个答案:

答案 0 :(得分:4)

declare @T table
(
  tableName varchar(20),
  uqName varchar(20),
  col1 varchar(10),
  col2 varchar(10)
)

insert into @T values
('TableName', 'UniqueKeyName', null, 'ABC')
insert into @T values
('TableName', 'UniqueKeyName', null, null)
insert into @T values
('TableName', 'UniqueKeyName', '123', '456')

select uqName as "@Name",
       tableName as "@TableName",
       (select 'col1' as "@Name",
               case when col1 is null then 'true' end as "@IsNull",
               col1 as "*"
        for xml path('Col'), type),
       (select 'col2' as "@Name",
               case when col2 is null then 'true' end as "@IsNull",
               col2 as "*"
        for xml path('Col'), type)
from @T
for xml path('UniqueKey')

结果:

<UniqueKey Name="UniqueKeyName" TableName="TableName">
  <Col Name="col1" IsNull="true" />
  <Col Name="col2">ABC</Col>
</UniqueKey>
<UniqueKey Name="UniqueKeyName" TableName="TableName">
  <Col Name="col1" IsNull="true" />
  <Col Name="col2" IsNull="true" />
</UniqueKey>
<UniqueKey Name="UniqueKeyName" TableName="TableName">
  <Col Name="col1">123</Col>
  <Col Name="col2">456</Col>
</UniqueKey>