Question

I am using Adventureworks2008R2 Database and trying to render the following. I have problem with Case clause in the SQL Query.

Enddate in the table is of date datatype

SELECT  
         Firstname,
            Lastname, 
            Startdate,
            'END DATE' =
              CASE   
                WHEN (ENDDATE is  null) Then 'Still Working'
                ELSE EndDate
               END
FROM 
     DIMEMPLOYEE

This is the error I get.

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

I know why it is coming but don't know easy fix? Update:

What all I want is When endate is not null then replace that column with 'still Working' String.

Was it helpful?

Solution

Would place a CAST around the EndDate column help you here. I think that the CASE statement is defining the column with a string datatype.

CASE
WHEN (EndDate IS NULL) THEN 'Still working'
ELSE CAST(EndDate AS VARCHAR)
END

OTHER TIPS

FWIW, here is the applicable CASE documentation:

The data types of input_expression and each when_expression must be the same or must be an implicit conversion ... [and also the] data types of else_result_expression and any result_expression must be the same or must be an implicit conversion.


Answering:

Why I should convert it to Varchar as I am not storing the data in the database, Select should render it?

The reason why this is a requirement (that CASE has a fixed result-type) is that each record (tuple) in the result-set must have the same type. The explicit coercion to VARCHAR, as pointed out in other answers, "widens" the data to a common type.

The schema for a result-set is separate from the data of the result-set itself and (at least in non-OORDMBS) is invariant (the CASE statement itself is contravariant through implicit conversions) -- that's "just the way SQL works", and it doesn't matter if the result-set is being fed into another select/join or back to a client. The "client" could very well be another server running a remote query ;-)

Imagine this invalid result-set (which is what SQL Server is rejecting):

schema: {int, date}
{1: int, 2001.10.22: date}
{2: int, "Hello world": string} <-- misshaped record! must agree with schema!

Happy coding.

You can also use coalesce

     Coalesc(cast(enddate as varchar), 'still working')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top