[英]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)
如果我取消“ +發布日期”,則效果很好。 但是用+發布日期,我得到這個錯誤:
從字符串轉換日期時間時轉換失敗。
除非posted為true,否則posteddate字段通常為null,並且posteddate的格式明確為datetime。
有任何想法嗎?
您需要將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)
我懷疑它是在抱怨您試圖在字符串中添加日期。 根據您使用的平台:
1)確保可以使用“ +”實現字符串連接。 您可能必須調用一個函數,例如CONCAT()
2)將日期轉換為字符串。
您要添加兩個具有不同類型的值,因此數據庫嘗試將其中一個轉換為另一種類型。
串聯之前將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
必須先將PostedDate視為字符串,然后才能將其連接到另一個字符串。 您可以通過這種方式進行轉換
CONVERT(varchar(10),發布日期,101)
CONVERT的語法:CONVERT(data_type [(length)],expression [,style])
樣式是可選的
以下是一些樣式示例:
101 = mm / dd / yyyy ex。 01/02/1999
102 = yy.mm.dd ex。 99.02.01
103 = dd / mm / yyyy ex。 1999年2月1日
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.