“从字符串转换日期和/或时间时转换失败”

问题描述 投票:0回答:1

早上好。我有以下代码的上述问题。

SELECT            c.Account_SPID__c [SPID]
                  ,CONVERT(DATE,c.Background_Check_Authorization_Date_Sent__c) [Sent]
                  ,CONVERT(DATE,c.BGC_Completion_Date__c) [Complete]
                  ,c.BGC_Status__c [BGC Status]
                  ,m2.market
                  ,a.billingstate
                  
FROM        SalesForceLocal_Reporting.dbo.Contact c WITH (NOLOCK)

inner join SalesForceLocal.dbo.Account a with (nolock) on c.account_spid__C = a.spid__C
inner join SalesForceLocal.dbo.market__C m with (nolock) on a.market__C = m.id
inner join angie.dbo.markets m2 with (nolock) on m.market_id__C = m2.marketid

where c.Background_Check_Authorization_Date_Sent__c >= DATEADD(year,-1,GETDATE())
and c.BGC_Status__c in ('pass','fail')
and c.BGC_Completion_Date__c is not null
and c.BGC_Completion_Date__c >= c.Background_Check_Authorization_Date_Sent__c

and c.background_check_authorization_date_sent__C not in 
('2023-04-18 10:45:00:00000')

如果我省略了排除特定时间戳的最终检查,它运行正常。但我实际上需要排除当时的所有条目。因此,问题出在该日期条目中的某处,但由于查询的性质,我一直无法找到格式错误的字符串,例如它正在验证需要什么日期,但在到达损坏/格式错误的条目时失败。如果我在“where”语句中省略日期验证,我会得到 4M 个结果。

感谢您的帮助!

sql sql-server date-conversion
1个回答
0
投票

假设 SQL Server 基于错误文本,我能够重现问题:

https://dbfiddle.uk/qqw13556

简而言之,日期文字末尾的 0 太多,你应该这样做:

and c.background_check_authorization_date_sent__C not in 
    ('2023-04-18T10:45:00.000')

还要注意日期和时间部分之间的额外

T
,这对于 SQL Server 来说确实是正确的,而原始版本则不是。如果您愿意,也可以这样做:

and c.background_check_authorization_date_sent__C not in 
    ('20230418 10:45:00.000')

但是再说一次:原始格式最终会给你带来麻烦,你应该避免它。

© www.soinside.com 2019 - 2024. All rights reserved.