Reputation: 7611
SELECT id,
sageaccount,
sageid,
totalwithoutvat,
vat,
total,
invoicedate,
alloweditting,
finished,
CASE WHEN isposted = 1 THEN 'Posted on ' + posteddate
ELSE 'Not Posted'
END AS Posted
FROM Invoices
WHERE (sageaccount = @sageaccount)
If I take the '+ posteddate' away, it works perfectly. But with the + posteddate, I get this error:
Conversion failed when converting datetime from character string.
The posteddate field is usually null, unless posted is true, and the format of posteddate is definetly datetime.
Any ideas?
Upvotes: 0
Views: 122
Reputation: 3078
the PostedDate must be treated as a string first before you can join it to another string. You can do a conversion this way
CONVERT(varchar(10), posteddate, 101)
Syntax for CONVERT: CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
style is optional
here are some samples of styles:
101 = mm/dd/yyyy ex. 01/02/1999
102 = yy.mm.dd ex. 99.02.01
103 = dd/mm/yyyy ex. 02/01/1999
Upvotes: 0
Reputation: 700192
You are adding two values with different types, so the database tries to convert one of them to the other type.
Convert the datetime value to a string before concatenating:
SELECT
id, sageaccount, sageid, totalwithoutvat, vat, total,
invoicedate, alloweditting, finished,
CASE
WHEN isposted = 1 THEN 'Posted on ' + convert(varchar, posteddate)
ELSE 'Not Posted'
END AS Posted
FROM Invoices
WHERE sageaccount = @sageaccount
Upvotes: 0
Reputation: 38825
I suspect it is complaining about you trying to add a date to a string. Depending on what platform you are using:
1) Ensure that string concatenation can be achieved with '+'. You might have to call a function instead such as CONCAT()
2) Cast the Date as a string.
Upvotes: 1
Reputation: 498
You need to convert posteddate to a varchar value in order to concatenate it with another varchar value ('Posted on ')
SELECT id,
sageaccount,
sageid,
totalwithoutvat,
vat, total,
invoicedate,
alloweditting,
finished,
CASE WHEN isposted = 1 THEN 'Posted on ' + CONVERT(varchar(10), posteddate, 20) ELSE 'Not Posted' END AS Posted
FROM Invoices
WHERE (sageaccount = @sageaccount)
Upvotes: 3