Date error in Stored Procedure

  • I have a stored procedure like such...

    Create   Procedure dbo.sp_TestSalesRanking @startdate varchar, @enddate varchar as

    select Agent,City,DateSold as TransDate,CalcSalesPrice as Saleprice,'Sale' as TransactionType,1 As Amt

    from all_regions_weekly_sales_report

    where datesold between @startdate and @startdate

    The date the user enters through the app needs to be in '4/1/2004' format.

    Why is it when you execute this

    exec sp_TestSalesRanking '4/1/2004','4/30/2004'

    I get an error...

    Server: Msg 241, Level 16, State 1, Procedure sp_TestSalesRanking, Line 5

    Syntax error converting datetime from character string.

    Yet if I run just the query as

    select Agent,City,DateSold as TransDate,CalcSalesPrice as Saleprice,'Sale' as TransactionType,1 As Amt

    from all_regions_weekly_sales_report

    where datesold between '4/1/2004' and '4/30/2004'

    It works perfectly fine!

    How can I change this to accept the '4/30/2004' format???

    Any help is greatly appreciated

  • CAST or CONVERT the variables to datetime, e.g.:

    where datesold between Cast(@startdate as Datetime) and Cast(@startdate as Datetime)

  • That doesn't work either through the procedure, I get the same error

  • This probably won't fix your problem, but your between is looking at the same two variables, startdate and startdate, instead of between startdate and enddate.


    J. Bagwell

    UVA Health System

  • Just a typo Janna, didn't fix anything

  • Cedar72,

    You've been bitten by the "time" element of datetime data types... try this as your WHERE clause...

    where datesold between DATEADD(dd,0,DATEDIFF(dd,0,@StartDate))
                       AND DATEADD(dd,0,DATEDIFF(dd,0,@EndDate))+'23:59:59.997'

    The DATEADD/DATEDIFF thingy accurately removes the time element without the rounding that occurs with INT conversions and also avoids CONVERT.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 6 posts - 1 through 5 (of 5 total)

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