Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 tsql query to get the data each day of the range

Author  Topic 

sqlservernovice
Starting Member

9 Posts

Posted - 2012-12-11 : 16:24:11
Declare @date1= '01-01-2012'
Select a.ID, a.locID, @date1 AS OperatingDate
from dataset A
where A.startDate <= @date1
AND (A.endDate >= @date1 or a.endDate is null)
AND A.condition <> 1

the data looks like this when execution of this query
id locID OperatingDate

716 30411 1-1-2011
828 10615 1-1-2011
.
.
some 100 records


But when given a range i want to get the data in the following format
id locID OperatingDate
7165 30411 1-2-2011
8284 10615 1-2-2011
.
.
some 100 records
7165 30411 1-3-2011
8284 10615 1-3-2011
.
.
some 92 records
7165 30411 1-4-2011
8284 10615 1-4-2011
.
.
some 99 records

How can i achieve it,not sure what would be the best option to use a while or cursor or a CTE

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-12-11 : 17:21:47
Do you mean something like this?
DECLARE @date1 DATETIME = '20120101'
DECLARE @date2 DATETIME = '20120430';
SELECT a.ID,
a.locID,
@date1 AS OperatingDate
FROM dataset A
WHERE A.startDate >= @date1
AND (A.endDate <= @date2 OR a.endDate IS NULL)
AND A.condition <> 1
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-12-14 : 02:03:32
till how many months you've to repeat this?

DECLARE @date1 DATETIME = '20120101'
DECLARE @date2 DATETIME = '20120430';

;With Months (N)
AS
(
SELECT 0
UNION ALL
SELECT N+1
FROM Months
WHERE DATEADD(mm,N+1,@date1) <=@date2
)
SELECT a.ID,
a.locID,
DATEADD(mm,N,@date1) AS OperatingDate
FROM dataset A
CROSS JOIN Months m
WHERE A.startDate >= @date1
AND (A.endDate <= @date1 OR a.endDate IS NULL)
AND A.condition <> 1


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -