所以我有這樣的代碼運行偉大:日期列將不轉換where子句
SELECT
QuoteDet.QuoteNo,
Quote.SalesID,
Quote.CustCode,
QuoteDet.PartNo AS [Version],
QuoteDet.Price1 AS [Unit Price],
CONVERT(VARCHAR(30), CAST(QuoteDet.User_Text1 AS DATE), 1) AS [Submittal Date]
FROM QuoteDet INNER JOIN Quote ON QuoteDet.QuoteNo = Quote.QuoteNo
WHERE QuoteDet.Status IN ('Req', 'Pend')
AND QuoteDet.User_Text1 <> 'HOLD'
GROUP BY QuoteDet.QuoteNo, Quote.SalesID, Quote.CustCode, QuoteDet.PartNo,
QuoteDet.Price1, QuoteDet.User_Text1
ORDER BY CONVERT(VARCHAR(30), CAST(QuoteDet.User_Text1 AS DATE), 1)
但是,當我在where子句中添加以下條件來得到當前一週,我得到的消息從字符串轉換日期或時間「轉換失敗
SELECT
QuoteDet.QuoteNo,
Quote.SalesID,
Quote.CustCode,
QuoteDet.PartNo AS [Version],
QuoteDet.Price1 AS [Unit Price],
CONVERT(VARCHAR(30), CAST(QuoteDet.User_Text1 AS DATE), 1) AS [Submittal Date]
FROM QuoteDet INNER JOIN Quote ON QuoteDet.QuoteNo = Quote.QuoteNo
WHERE QuoteDet.Status IN ('Req', 'Pend')
AND CONVERT(VARCHAR(30), CAST(QuoteDet.User_Text1 AS DATE), 1) >=
DATEADD(DAY, 1-DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))
AND CONVERT(VARCHAR(30), CAST(QuoteDet.User_Text1 AS DATE), 1) <
DATEADD(DAY, 8-DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))
AND QuoteDet.User_Text1 <> 'HOLD'
GROUP BY QuoteDet.QuoteNo, Quote.SalesID, Quote.CustCode, QuoteDet.PartNo,
QuoteDet.Price1, QuoteDet.User_Text1
ORDER BY CONVERT(VARCHAR(30), CAST(QuoteDet.User_Text1 AS DATE), 1)
爲什麼我沒有拿到第一個查詢錯誤?它也轉換爲日期,但沒有錯誤
提示:'GetDate()'在查詢中有點奇怪。每個_instance_在查詢中都有一個常量值。例如'select D1(GetDate(),GetDate()as SomeTable'中的D2可能爲兩列返回兩個不同的值,但它們不會因行而變化。當在多個語句中使用'GetDate()'時,例如在存儲過程中,可以通過獲取單個值並在整個過程中使用它,即'declare @Now as DateTime = GetDate();'並根據需要使用'@ Now'來避免有趣的意外。 – HABO