Build <options> tags with FOR XML Path in SQL. Remove unwanted Attributes

StackOverflow https://stackoverflow.com/questions/9430453

  •  12-11-2019
  •  | 
  •  

سؤال

Probably a really simple question to answer but I can't for the life of me find it anywhere.

I'm looking to build select list options from the database using FOR XML Path. So far I have this:

SELECT ID AS 'option/@value', Name AS [option]
FROM MyTable
FOR XML Path('')

Which gets me this:

<option value="1">Item 1</option><option value="2">Item 2</option>... and so on

Yep pretty simple stuff but now I want to set which option is selected where ID is lets say 1. So this should only ever occur once. So I add this:

SELECT 
    ID AS 'option/@value', Name AS [option],
    CASE WHEN ID=1 THEN 'selected' ELSE '' END AS 'option/@selected',
FROM MyTable
FOR XML Path('')

Output:

<option value="1" selected="selected">Item1</option><option value="2" selected="">Item2</option>

Although this does technically set the right attribute I only need the attribute @selected on options where the case is true.

Any help or point in the right direction would be greatly received.

هل كانت مفيدة؟

المحلول

Instead of using a empty string in your case statement return a Null

SELECT 
    ID AS 'option/@value', 
    CASE WHEN ID=1 THEN 'selected' ELSE null END AS 'option/@selected',
    Name AS [option]    
FROM MyTable
FOR XML Path('')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top