Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
SQL
GO
/****** Object:  Table [dbo].[Tbl_User_Vacation]    Script Date: 11/04/2014 18:22:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Tbl_User_Vacation](
	[User_Vacation_ID] [int] IDENTITY(1,1) NOT NULL,
	[User_ID] [int] NULL,
	[Leave_Date] [datetime] NULL,
	[Leave_Reason] [varchar](2550) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[Expected_Return] [datetime] NULL,
	[Actual_return] [datetime] NULL,
 CONSTRAINT [PK_Tbl_User_Vacation] PRIMARY KEY CLUSTERED 
(
	[User_Vacation_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF


It is the table which have the fields to enter leave date from expected return that gives an range for the leave I need an result that has a date on rows eg.
Need userid "1" leave from 30-10-14 to 5-11-14
the result should be

[User_Vacation_ID] | Date
=======================|============================
1 | 30-10-14
1 | 31-10-14
1 | 1-11-14
1 | 2-11-14
1 | 3-11-14
1 | 4-11-14
Posted

I prefer CTE[^] rather than WHILE loop ;)
SQL
DECLARE @startDate DATETIME = '2014-10-30'
DECLARE @finishDate DATETIME = '2014-11-04' 
;WITH MyDates AS
(
    SELECT @startDate AS MyDate
    UNION ALL 
    SELECT DATEADD(DD,1,MyDate) AS MyDate
    FROM MyDates
    WHERE DATEADD(DD,1,MyDate)<=@finishDate
)
INSERT INTO TableName (User_Vacation_ID, [Date])
SELECT 1 AS User_Vacation_ID, MyDate AS [Date]
FROM MyDates
 
Share this answer
 
v2
Comments
Manas Bhardwaj 4-Nov-14 10:27am    
CTE rocks +5
Maciej Los 4-Nov-14 10:34am    
Thank you, Manas ;)
DamithSL 4-Nov-14 10:39am    
5wd!
Maciej Los 4-Nov-14 10:42am    
Thank you ;)
sample code:
SQL
SET @CurrentDate = @startDate

WHILE @CurrentDate <= @endDate
BEGIN
    INSERT INTO TableOfDates(User_Vacation_ID,DateValue) VALUES (@ID, @CurrentDate)

    SET @CurrentDate = DATEADD(DAY, 1, @CurrentDate)
END
 
Share this answer
 
Comments
Manas Bhardwaj 4-Nov-14 10:27am    
Yes +5!
DamithSL 4-Nov-14 10:31am    
Thank you, Manas
Maciej Los 4-Nov-14 10:36am    
+5!
DamithSL 4-Nov-14 10:38am    
Thanks Maciej

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900