Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion failed when converting date and/or time from character string

I have a fairly simple pagination query used to get rows from a table

ALTER PROCEDURE mytable.[news_editor_paginate]
    @count int,
    @start int,
    @orderby int
AS
BEGIN
    SET NOCOUNT ON;
    SELECT TOP (@count) * FROM 
    (  
        SELECT news_edits.*,
        ROW_NUMBER() OVER (
            ORDER BY CASE 
                WHEN @orderby = 0 THEN news_edits.[time]
                WHEN @orderby = 1 THEN news_edits.lastedit
                WHEN @orderby = 2 THEN news_edits.title
                END
            DESC
        ) AS num
        FROM news_edits
    ) AS a
    WHERE num > @start
END

The @orderby parameter decides which column the results should be ordered by.

news_edit.[time] and news_edits.lastedit are both datetime fields. But news_edits.title is a varchar field.

The query runs fine for both the datetime fields but when @orderby = 2 I get the following error:

"Conversion failed when converting date and/or time from character string."

The problem I'm having is that I'm not trying to convert anything?

like image 586
James Hay Avatar asked Apr 03 '12 22:04

James Hay


People also ask

How do I fix conversion failed when converting date and or time from character string error?

The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings. YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important!

How do I fix conversion failed when converting date and or time from character string in SQL Server?

To solve your issue you can use the ISO-8601 date format that is supported by SQL Server. The ISO-8601 format is supported by SQL Server comes in two flavors: YYYYMMDD for just dates. YYYY-MM-DDTHH:MM:SS for dates and times.

How do you resolve the conversion of a varchar data type to a datetime data type resulted in an out of range value?

Answer: The error is due to an invalid date format being saved to the custom_rmh_rooms_history SQL table. To resolve this issue, the Windows Regional settings need to be modified and the Short Date format needs to be in MM/dd/yyyy format.


1 Answers

You'll need to divide your ORDER BY into multiple CASE statements:

ORDER BY 
    CASE WHEN @orderby = 0 THEN news_edits.[time] END DESC,
    CASE WHEN @orderby = 1 THEN news_edits.lastedit END DESC,
    CASE WHEN @orderby = 2 THEN news_edits.title END DESC

This is because single CASE statement requires that all branches have compatible data types. Since your character string in one CASE can't be converted to the date time returned from another CASE, you get the conversion error.

like image 84
Michael Fredrickson Avatar answered Oct 28 '22 07:10

Michael Fredrickson