2015-05-01 105 views
1

我用下面的SQL查詢工作,我得到了以下錯誤:消息轉換爲varchar日期類型爲datetime錯誤SQL

242, Level 16, State 3, Line 1 The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

我的SQL查詢看起來是這樣的:

SELECT  customer_del_hist.customer_number, MAX(customer_del_hist.serve_location) AS serve_location, MAX(customer_del_hist.product_number) AS product_number, 
         MAX(customer_del_hist.del_date) AS del_date, MAX(order_rte_bal.warehouse) AS warehouse, MAX(order_rte_bal.route_number) AS route_number, 
         MAX(order_rte_bal.route_day) AS route_day 
FROM   customer_del_hist INNER JOIN 
         inv_master ON customer_del_hist.product_number = inv_master.product_number INNER JOIN 
         order_header ON customer_del_hist.order_number = order_header.order_number INNER JOIN 
         order_rte_bal ON order_header.warehouse_number = order_rte_bal.warehouse AND order_header.route_number = order_rte_bal.route_number AND 
         order_header.route_day = order_rte_bal.route_day AND order_header.delivery_date = order_rte_bal.route_date 
WHERE  (customer_del_hist.del_date BETWEEN '5/01/2015' AND '7/31/2015') AND (inv_master.inventory_category IN ('02', '03', '60', '74')) AND 
         (customer_del_hist.customer_number NOT IN 
          (SELECT  h2.customer_number 
           FROM   customer_del_hist AS h2 INNER JOIN 
                 inv_master AS i ON h2.product_number = i.product_number 
           WHERE  (h2.del_date BETWEEN '6/01/2014' AND '4/31/2015') AND (i.inventory_category IN ('02', '03', '60', '74')))) 
GROUP BY customer_del_hist.customer_number 

我已經查看了必要表格中的日期,並且顯示與以下類似的內容:2014-05-21 00:00:00.000。任何關於解決或解決問題的想法?

+0

你確定沒有無效數據在專欄,可能是'2014-13-01 00:00:00.000' – Hogan

回答

-1

具有日期時間字符串的CAST和CONVERT的行爲由SET DATEFORMAT進行管理。如果您的日期格式爲dmy(日/月/年),則您的文字'7/31/2015'可能會被解釋爲{月:31,日:7,年:2015},這不是有效的日期。

在這裏看到: SET DATEFORMAT (Transact-SQL)

一件事,這將有助於你在這種情況下是要始終使用ISO 8601格式的這些文字。這將繞過CAST和CONVERT的解釋行爲。

對於你的情況,你可以把它改寫爲:

customer_del_hist.del_date BETWEEN '2015-05-01' AND '2015-07-31' 
0

這個問題實際上是有隻有30天在四月,沒有31

相關問題