[英]What's wrong with my SQL query?
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. 除非posted为true,否则posteddate字段通常为null,并且posteddate的格式明确为datetime。
Any ideas? 有任何想法吗?
You need to convert posteddate to a varchar value in order to concatenate it with another varchar value ('Posted on ') 您需要将postddate转换为varchar值,以便将其与另一个varchar值连接(“ 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)
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 '+'. 1)确保可以使用“ +”实现字符串连接。 You might have to call a function instead such as CONCAT()
您可能必须调用一个函数,例如CONCAT()
2) Cast the Date as a string. 2)将日期转换为字符串。
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: 串联之前将datetime值转换为字符串:
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
the PostedDate must be treated as a string first before you can join it to another string. 必须先将PostedDate视为字符串,然后才能将其连接到另一个字符串。 You can do a conversion this way
您可以通过这种方式进行转换
CONVERT(varchar(10), posteddate, 101) CONVERT(varchar(10),发布日期,101)
Syntax for CONVERT: CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) CONVERT的语法:CONVERT(data_type [(length)],expression [,style])
style is optional 样式是可选的
here are some samples of styles: 以下是一些样式示例:
101 = mm/dd/yyyy ex. 101 = mm / dd / yyyy ex。 01/02/1999
01/02/1999
102 = yy.mm.dd ex. 102 = yy.mm.dd ex。 99.02.01
99.02.01
103 = dd/mm/yyyy ex. 103 = dd / mm / yyyy ex。 02/01/1999
1999年2月1日
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.