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
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Date quereis

Author  Topic 

abhit_kumar
Posting Yak Master

147 Posts

Posted - 2009-09-12 : 01:26:32
Hello All friends,

I have some problem in writing stored procedure for date related quereis.

There is two date field which is of mm/dd/yyyy format.

Suppose First date field = 02/21/2008
Second date field = 11/15/2009

Now i want to calculate number of days return based upon the condition as below:-

It will should retrun to split into the number of days in 2008 and the number of days in 2009.

And the number of days return for 2008 should be used for some other calc and number of days return for 2009 should be used for some different calc.

year 2008 period is = 01/01/2008 to 12/31/2008
year 2009 period is = 01/01/2009 to 12/31/2009

Please help me in respect of same.

Thanks,
Abhi

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2009-09-12 : 07:33:03
[code]DECLARE @Sample TABLE
(
a DATETIME,
b DATETIME
)

INSERT @Sample
SELECT '20080221', '20091115' UNION ALL
SELECT '20080909', '20081111'

DECLARE @Tally TABLE
(
i INT
)

INSERT @Tally
SELECT 256 * v1.Number + v2.Number
FROM master..spt_values AS v1
INNER JOIN master..spt_values AS v2 ON v2.Type = 'P'
WHERE v1.Type = 'P'
AND v1.Number < 256
AND v2.Number < 256

SELECT s.a,
s.b,
DATEPART(YEAR, DATEADD(DAY, t.i, s.a)) AS theYear,
COUNT(*) AS theDays
FROM @Sample AS s
INNER JOIN @Tally AS t ON t.i <= DATEDIFF(DAY, s.a, s.b)
GROUP BY s.a,
s.b,
DATEPART(YEAR, DATEADD(DAY, t.i, s.a))
ORDER BY s.a,
s.b,
DATEPART(YEAR, DATEADD(DAY, t.i, s.a))[/code]The @Tally table is good for about 179 years date span.


N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2009-09-12 : 07:34:43
Oh... The result from above suggestion is
a		b		theYear	theDays
2008-02-21 2009-11-15 2008 315
2008-02-21 2009-11-15 2009 319
2008-09-09 2008-11-11 2008 64



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
   

- Advertisement -