3

I have the following SQL query that I'm having trouble explicitly defining the shape for

select tableName, uqName, col1, col2
from someTable

I would like to select the results into XML as below. I need the col1 and col2 to show up as children and tableName and uqName to show up as attributes. If col1 or col2 is null then I need to specify an IsNull attribute. Otherwise the value is selected as a text node as the child of the Col element

One row returned from the above SQL would look like this:

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

How can I explicitly define this XML shape using SQL Server 2008 R2?

5
  • You know about the SQL COALESCE function right? Commented Mar 19, 2012 at 7:47
  • Also, do you want the XML as result of the SELECT or can you select into a buffer/file/pipe/etc. and then work on that to shape the result? Commented Mar 19, 2012 at 7:48
  • Ideally I could get this result directly as a result of the select Commented Mar 19, 2012 at 7:49
  • what SQL engine are you using then? Commented Mar 19, 2012 at 7:52
  • sorry, can't help you there, never worked with that Commented Mar 19, 2012 at 7:56

1 Answer 1

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')

Result:

<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>
Sign up to request clarification or add additional context in comments.

1 Comment

@RoyiNamir Yes agreed. I took mine off. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.