2017-04-05 35 views
0

我有一份报告停止在生产环境中工作,直到几个星期前它工作正常。它使用相同的代码在dev中工作正常。这两种环境中的SQL Server 2012日期转换在PROD上失败,在DEV中正常工作

select SUM(oi.quantity_shipped) as [Quantity Shipped], 
    oi.itemDescription as [Item Description], 
    oi.itemLanguage 
from order_items as oi 
inner join orderX as x on oi.ID = x.id 
where convert(date, x.shipDate) between '1/1/2016' and '1/1/2017' 
group by oi.itemDescription, 
    oi.itemLanguage 
order by [Item Description] 

督促代码返回错误:

Msg 241, Level 16, State 1, Line 2 Conversion failed when converting date and/or time from character string.

注意,x.shipDate可以是零。任何想法是什么导致这个?

+0

我的数据库中shipDate的格式是varchar,当它包含一个值时,它的格式如下:2017-01-25 – user2055729

+0

在x.shipdate字段中有一个错误的值。如果可以,请将该列的数据类型更改为datetime – SQLMason

+0

您还应该使用ANSI标准日期格式的字符串。 YYYY-MM-DD。这是唯一的字符串格式,无论dateformat如何都将始终工作。 –

回答

0

看起来你在约会现场一些不好的数据,你可以按照以下使用try_convert离开这些转换错误:

select SUM(oi.quantity_shipped) as [Quantity Shipped], 
    oi.itemDescription as [Item Description], 
    oi.itemLanguage 
from order_items as oi 
inner join orderX as x on oi.ID = x.id 
where try_convert(date, x.shipDate) between '1/1/2016' and '1/1/2017' 
group by oi.itemDescription, 
    oi.itemLanguage 
order by [Item Description] 
+0

请注意,'try_convert'是2012 + – SQLMason

+0

是不支持,Msg 195,Level 15,State 10,Line 7 'try_convert'不是一个公认的内置函数名称。 – user2055729

1

即使你发现了糟糕的数据导致你的错误,这里有一些其他的事情请记住:

我想你可能会误解between;除非您明确希望包含2017年1月1日的所有内容。另外,还可以使用日期的'YYYYMMDD'字符串格式。

Applications that use other APIs, or Transact-SQL scripts, stored procedures, and triggers, should use the unseparated numeric strings. For example, yyyymmdd as 19980924. - Write International Transact-SQL Statements - msdn

select SUM(oi.quantity_shipped) as [Quantity Shipped], 
    oi.itemDescription as [Item Description], 
    oi.itemLanguage 
from order_items as oi 
inner join orderX as x on oi.ID = x.id 
where convert(date, x.shipDate,120) >= '20160101' 
    and convert(date, x.shipDate,120) < '20170101' 
group by oi.itemDescription, 
    oi.itemLanguage 
order by [Item Description] 

参考:

-1

找到它 - !数据错误,我的外部系统在0000-00-00 for shipDate中输入! 感谢所有的提示和建议。

相关问题