t-sql date question

  • My requirement is if the startdate and enddate parameters are null, then

    the dates should default to last week, sunday(startdate) - saturday(enddate),

    otherwise, it should take the supplied parameters.

    I am planning to write the below code for that, please let me know if there is a better way

    of doing that. Thanks.

    create proc proc1

    @startdate datetime = null,

    @enddate datetime = null

    as

    IF @STARTDATE IS NULL AND @ENDDATE IS NULL

    IF DATENAME(dw, GETDATE()) = 'Sunday'

    SET @STARTDATE = getdate()-7 --SUNDAY

    SET @ENDDATE = GETDATE()-1 --SATURDAY

    IF DATENAME(dw, GETDATE()) = 'Monday'

    SET @STARTDATE = getdate()-8 --SUNDAY

    SET @ENDDATE = GETDATE()-2 --SATURDAY

  • Can you provide a concrete example of what you are talking about? For instance, what dates would be used today (2009-03-31) if either or both paramteres are null.

  • Does this code help:

    declare @ThisDate datetime;

    set @ThisDate = getdate();

    select dateadd(wk, datediff(wk, 0, @ThisDate) - 1, -1), -- Beginning of previous week (Sunday)

    dateadd(wk, datediff(wk, 0, @ThisDate) - 1, -1) + 6 -- ending of previous week (Saturday)

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply