将varchar转换为datetime的SQL查询

时间:2016-08-29 11:49:13

标签: sql-server

SELECT distinct 
    (Client_Name),
    AMC_Expiry as date,
    Dealer_Name,
    Location,
    Product_Type, Product_Name,
    Quantity, 
    Install_Date, Warranty_Expiry, AMC_Expiry,
    mail_sent,
    billing_by, callhandled_by   
FROM 
     amc 
WHERE   
    (datediff(day, cast(convert(datetime, AMC_Expiry, 103) as datetime),  
                   cast(convert(datetime, GETDATE(), 103) as datetime)) > '-30'   
    and datediff(day, cast(convert(datetime, AMC_Expiry, 103) as datetime),
                      cast(convert(datetime, GETDATE(), 103) as datetime))  < 1)     
    and mail_sent = 'N'   
    or (datediff(day, cast(convert(datetime, Warranty_Expiry, 103) as datetime),
                      cast(convert(datetime, GETDATE(), 103) as datetime)) > '-30'
    and datediff(day, cast(convert(datetime, Warranty_Expiry, 103) as datetime),
                      cast(convert(datetime, GETDATE(), 103) as datetime))  < 1) 
    and mail_sent = 'N'

1 个答案:

答案 0 :(得分:2)

评论太长了。

首先,您似乎误解了select distinctDISTINCT 不是一个函数。它是适用于所有列的子句的一部分。

其次,你做的很荒谬:

cast(convert(datetime,GETDATE(),103) as datetime))

为什么要获取datetime值,将其转换为datetime,然后将其重新转换为datetime

此外,您在WHERE子句中有逗号,这没有任何意义。并且,您在单引号中有整数常量。

您的查询比您提到的问题有更多问题。