Question

select packageid,status+' Date : '+UpdatedOn from [Shipment_Package] 

The below error is appeared when executing the above code in sql server. The type of UpdatedOn is DateTime and status is a varchar. We wanted to concatenate the status, Date and UpdatedOn.

error:

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

Was it helpful?

Solution

You need to convert UpdatedOn to varchar something like this:

select packageid, status + ' Date : ' + CAST(UpdatedOn AS VARCHAR(10))
from [Shipment_Package];

You might also need to use CONVERT if you want to format the datetime in a specific format.

OTHER TIPS

To achive what you need, you would need to CAST the Date?

Example would be;

Your current, incorrect code:

select packageid,status+' Date : '+UpdatedOn from [Shipment_Package] 

Suggested solution:

select packageid,status + ' Date : ' + CAST(UpdatedOn AS VARCHAR(20))
from [Shipment_Package] 

MSDN article for CAST / CONVERT

Hope this helps.

To account for null values, try this:

select packageid, 
    'Status: ' + isnull(status, '(null)') + ', Date : ' 
    + case when UpdatedOn is null then '(null)' else convert(varchar(20), UpdatedOn, 104) end as status_text
from [Shipment_Package]

Convert Datetime column into varchar for sql Server you can use below code

select packageid,status+' Date : '+CONVERT(VARCHAR,UpdatedOn,120) from [Shipment_Package] 

120 code will convert your date into this format : 2020-06-12 15:09:00 other format you can use from this link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top