Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Comma separated values SQL [duplicate]

I have a field names DAILYREPORT.WEATHERCONDITION which can hold values as '1,2,3' or '1' or '2,4' based on what the user selects from the list of weather check boxes available to him. The weather table contains the list of weathers which he selects

Weather Table

ID  Condition
----------

1   Sunny    
2   Cloudy
3 Fine    
4 Windy 

Now i need a query which returns the conditions as 'Sunny,Cloudy,Fine' when DAILYREPORT.WEATHERCONDION=1,2,3

like image 491
user1699025 Avatar asked Dec 20 '25 19:12

user1699025


2 Answers

Try this :

SELECT STUFF
(
     (select ',' + Condition
      from
      Weather
      where 
      ID in (1,2,3)
      FOR XML PATH('')
      ),1,1,''
)
like image 158
Krishna Avatar answered Dec 22 '25 12:12

Krishna


DECLARE @list VARCHAR(MAX)
SELECT @list = COALESCE(@list+',' ,'') + Condition
FROM Weather
WHERE ID IN (1,2,3)
SELECT @list

You declare a @list variable of varchar type. Then using the COALESCE expression (please look here http://msdn.microsoft.com/en-us/library/ms190349.aspx for further details on how it works) you get what you want.

That's a SQL fiddle that show that the above works as it is expected

http://sqlfiddle.com/#!6/65df2/1

Note : In order to avoid any misconception, I don't say that the COALESCE solves the stated problem.

It is is only there to deal with initializing the string and the issue of a extra comma at the end.

as Mikael wrote below.

like image 29
Christos Avatar answered Dec 22 '25 11:12

Christos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!