如果我在where子句中使用它,则日期列不会转换

时间:2017-09-21 22:47:54

标签: sql-server tsql

所以我的代码运行得很好:

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子句中添加以下条件以获取当前周时,我收到消息&#34;转换失败时从字符串转换日期和/或时间

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)

为什么我没有在第一个查询中收到错误?它也转换为日期,但没有错误

2 个答案:

答案 0 :(得分:1)

在您的第一个查询中,您是:

  • 首先投出&#39; QuoteDet.User_Text1&#39;作为日期
  • 然后将结果转换为长度为30的VARCHAR,产生一个字符串

在第二个查询中,您尝试使用字符串检查日期。你应该在WHERE子句中做的是删除&#39;转换&#39;方法调用,只需使用&#39; Cast&#39;方法。所以不要这样:

    CONVERT(VARCHAR(30), CAST(QuoteDet.User_Text1 AS DATE), 1)

您必须在WHERE子句中使用以下内容:

    CAST(QuoteDet.User_Text1 AS DATE)

答案 1 :(得分:1)

另一种可能性,第一个查询有效,因为select子句中的转换发生在由where子句缩小行之后。通过将转换移动到where子句,它现在可以在所有行上运行,其中一些行可能具有不能通过第一个查询中的select子句的错误数据。

如果您使用的是足够新版本的SQL Server,TRY_PARSE将通过为不可转换的字符串返回NULL来允许无错误的转换。