Home Forums SQL Server 2005 T-SQL (SS2K5) Conversion failed when converting datetime from character string RE: Conversion failed when converting datetime from character string

  • Well spotted, WayneS.

    Apart from that error in the string manipulation, it's better (for performance and to avoid internationalization issues) not to use string manipulation at all on your datetime values. The functions datediff() and dateadd() were designed to manipulate those values.

    To retrieve the first day of the current month you can use:

    select dateadd(month, datediff(month, 0, getdate()), 0)

    Next month's first day is:

    select dateadd(month, datediff(month, 0, getdate()), 1)

    Similar, to strip off the time part from any datetime value (= find the beginning of the day, 00:00:00.000 in the time component), use:

    select dateadd(day, datediff(day, 0, getdate()), 0)

    Plus, you're using between on datetime values. Since between is inclusive, you should better use "where @dtvalue >= @dtFromValue and @dtvalue < @dtToValue" instead of "where @dtValue between @dtValueFrom and @dtValueTo" to avoid incorrectly getting rows for the first day of the next month included in your results.



    Posting Data Etiquette - Jeff Moden[/url]
    Posting Performance Based Questions - Gail Shaw[/url]
    Hidden RBAR - Jeff Moden[/url]
    Cross Tabs and Pivots - Jeff Moden[/url]
    Catch-all queries - Gail Shaw[/url]


    If you don't have time to do it right, when will you have time to do it over?