Sometimes we need a resultset in SQL that should list all dates of a particular month.
For example, you want to return a resultset containing total of all expenses done against each date. But for that your expense table not necessary to contain entry of each and every date.
There may be some dates for which there is no expense, and simply that date will not be in the expense table.
In such scenarios you would always need to have one resultset (virtual table) containing list of all dates, which you can use to join (Left Join, ideally) with your expenses table by dates to get your desired result.
This is possible using CTE by performing recursive SELECT.
Following is the complete SQL Query to generate list of all dates for a particular month:
Image: Resultset after executing below SELECT Query
P.S. - There are actually 31 rows, its just due to screen truncate it showing 27 in image.
DECLARE @MonthName VARCHAR(3)
DECLARE @Year VARCHAR(4)
DECLARE @MaxDay INT
SET @MonthName = 'MAR'
SET @Year = '2012'
SET @MaxDay = 31;
WITH CTE_MonthDays AS (
SELECT 1 AS fldDay,
CONVERT(datetime, '1/' + @MonthName + '/' + @Year) AS fldDate
UNION ALL
SELECT fldDay + 1,
CONVERT(Datetime, CONVERT(varchar(2), fldDay + 1) + '/' + @MonthName + '/' + @Year) AS fldDate
FROM CTE_MonthDays
WHERE
fldDay + 1 <= @MaxDay
)
SELECT fldDate FROM CTE_MonthDays
Wednesday, April 11, 2012
Subscribe to:
Post Comments (Atom)
Blog Archive
-
▼
2012
(49)
-
▼
April
(24)
- Get only Date part for SQL Server DateTime value
- Membership in ASP.NET MVC 4 (System.Web.Providers)
- Binding two or more types of objects (models) to s...
- Implement Custom Validation in ASP.NET MVC
- Simple client-side Validations using ASP.NET MVC
- Investigation: Values do not retain in model while...
- Data Binding to RadioButton in a View in MVC
- Investigation: SelectedIndexChanged not firing for...
- Investigation: ExecuteNonQuery() always returns -1
- Development and Deployment - Troubleshooting, Inve...
- Print Page Content to printer (or virtual print ou...
- Show long text in Tooltip
- Auto login into Team system with your authorized c...
- Visual Studio .NET - Some handy shortcuts
- Write custom events for User Controls in ASP.NET
- SQL Query to return each date of month in each dif...
- How to debug ASP.NET Windows Service
- FIX: Add a 32-bit SQL Server 2000 as a Linked serv...
- Difference between integer Cast and Convert in C#
- Optimizing SQL Code by replacing IF..ELSE with CAS...
- Check Authentication Mode in ASP.NET
- How to validate a page using Java script
- SQL Query - To search for a column (by column name...
- C#.NET - Difference between Convert.ToString(), .T...
-
▼
April
(24)
Excellent solution.....
ReplyDelete