2010-11-05 87 views
0
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) 

如果我把'+ posteddate'去掉了,它可以很好地工作。但是,用+發佈日期,我得到這個錯誤:我的SQL查詢出了什麼問題?

轉換日期時間從字符串轉換失敗。

posteddate字段通常爲空,除非發佈爲真,並且publishdate的格式是definetly日期時間。

任何想法?

+2

您正在使用哪個供應商? MySQL的? SQL Server? http://www.1keydata.com/sql/sql-concatenate.html。如果你使用的是SQL Server,那麼(我認爲)解決的辦法是將'postingdate'作爲'varchar'。 – 2010-11-05 14:08:20

+0

對於MySQL CONCAT('Posted on',posteddate) – 2010-11-05 14:14:12

回答

3

您需要posteddate轉換爲VARCHAR值,以便與其他VARCHAR值(「發佈」)

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

值得注意的是'CONVERT'只適用於SQL Server。 – JNK 2010-11-05 14:11:46

1

我懷疑這是在抱怨你想將日期加到一個字符串來連接它。取決於你使用的平臺:

1)確保字符串連接可以用'+'來實現。您可能需要調用一個函數,如CONCAT()

2)將日期轉換爲字符串。

0

您正在使用不同類型添加兩個值,因此數據庫會嘗試將其中一個值轉換爲另一個類型。

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 
0

的PostedDate必須作爲一個字符串之前,首先你可以將其加入另一個字符串處理。 可以執行轉換這樣

CONVERT(VARCHAR(10),posteddate,101)

語法CONVERT: CONVERT(DATA_TYPE [(長度)],表達[,樣式])

風格是可選

這裏是樣式一些樣品:

101 =毫米/日/年離。 01/02/1999

102 = yy.mm.dd ex。例如:99.02.01

103 = dd/mm/yyyy ex。 02/01/1999

+1

同樣,'CONVERT'特定於SQL Server。 – JNK 2010-11-05 14:30:22

+0

我明白你的意思了......所以你想要一個ansi查詢在所有供應商(oracle,mysql,sql server等)上工作。 – 2010-11-05 15:01:47