SQL Server: How to concatenate string constant with date?
Asked Answered
S

4

11
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.

Sudatory answered 23/10, 2013 at 11:18 Comment(1)
is there at least one word null in the text of the question?Jecoa
S
16

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.

Spiffing answered 23/10, 2013 at 11:20 Comment(0)
U
1

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.

Unwinking answered 23/10, 2013 at 11:22 Comment(0)
I
1

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]
Indium answered 23/10, 2013 at 11:30 Comment(0)
A
1

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

Adriell answered 12/6, 2020 at 9:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.