Daily Archives: Sep 8, 2014


Avoid Use of While Loops to get a Comma Seperated list of rows 1

Problem Detail

In the morning at your workplace, your manager or any colleague comes to you and asks to get the list of all the dates in a comma separated list.

Now the first and the quickest way of getting the output which will knock us is using a loop to get the list.

In above case, DB engine has to iterate for each and every value of day and do the same task again and again. The same thing can be implementedin SET based approach using COALESCE function with a table which holdspre-filled dates for some period.

Imagine we have a table named cmn_Dates, which holds the dates for some predefined periods. Using that table we can write a query like below;

Conclusion: –

If you are thinking that why we will create a table and insert all the dates for some given periods (10 years or 20 years), … More