SQL Variable date minus a year

Readamus picture Readamus · Nov 20, 2013 · Viewed 7.8k times · Source

I have a stored proc which has a user input of a date (YYYMMDD).

To build the final part of the query I need to get the date that has been input to the date 12 months ago.

I have tried a few different methods such as casting it as datetime or dateadd functions but still no luck: below is a snipit of my code:

@DateSelected datetime=null,
@year int=null,
@week int=null,
@DayOfWeek int=null,
@DateSelectedLastYear datetime=null
--@Day int=null
as
begin
    --if date parms are null get current week and year
    if (@DateSelected is null)
        begin
            select @Year=year_number,@Week=week_number,@DayOfWeek=day_of_week from infrastructure..calendar
            where calendar_date=DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()-1))
        end
    else
    begin
        select @Year=year_number,@Week=week_number,@DayOfWeek=day_of_week from infrastructure..calendar
        where calendar_date=@DateSelected
    end
    begin
    Select
         @DateSelectedLastYear = DATEADD(YYYY,-1,@DateSelected)
    end

Answer

rory.ap picture rory.ap · Nov 20, 2013

Try this out:

select dateadd(year, -1, getdate())