views:

41

answers:

2

First I need to create a sproc that will give me just a list of years from this year back to 5 years before this year. I was thinking of somehow using a table variable?

After that I need to use that value as a parameter in another sproc. How would I then say show all Dates that contain the year that is picked? I know how to write the parameter and everything I just need the Where clause part of it.

The date in the column are like this 2010/01/30 00:00.000

+3  A: 

Part One:

Declare @Years Table (int year primary Key Not Null)
Declare @Yr integer Set @Yr = Year(getDate())
Declare @tYr Integer Set @tYr = @Yr
while @Yr > @TYr - 5 Begin
   Insert @Years(year) Values (@Yr)
   Set @Yr = @Yr - 1
End

Part TWO: (I assume you mean "Show all Dates That contain a year in the five year span" ??)

Where Year(dateColumn) In (Select year from @Years)

-- But this is not SARGable, so I would reccomend instead,

Where dateColumn Between DateAdd(year, Year(getDate())-1905, 0) 
                     And DateAdd(year, Year(getDate())-1899, 0) 
Charles Bretana
A: 

As an option you could use a temp table to store whatever years you need then drop it when your finished with it.

This example below will create a temp table with the following values. (2009, 2008, 2007, 2006, 2005)

-- Create Temp table
CREATE TABLE #years 
(
    [year]  int,
)

DECLARE @Max AS INT
DECLARE @Count AS INT

SET @Max = 5
SET @Count = 1

WHILE @Count <= @Max
BEGIN 

    INSERT INTO #years ([year])
    VALUES (YEAR(GETDATE())- @Count)
    SET @Count = @Count + 1

END

SELECT * FROM #years
--DR0P TABLE #years
kevchadders
If I use this as a seperate sproc to make a list of years how would I thne call this in my original sproc?
With the temp table built you could loop through it and pass each value as a parameter. Or with the code above where i have VALUES (YEAR(GETDATE())- @Count), could be where you call your original Sproc
kevchadders