从字符串转换日期和/或时间时,错误转换失败

时间:2019-07-19 11:58:37

标签: sql-server

我正在尝试运行以下代码。我收到一条错误消息

  

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

问题列为Policy_Txn_DatePolicy_Txn_Post_Date

policy_txn_date  policy_txn_post_date
--------------------------------------
20070131         20070201 
20070228         20070301 
20070331         20070401 
20070430         20070502 
20070531         20070604 
20060630         20060701 

代码:

select 
    'NLFMF' as Source_code,
    gPolicy_Number_static,
    gPolicy_Number,
    PolicyNumber as Policy_Number,
    TransactionGroup,
    TransactionType,
    Txn_Amount,
    cast(Policy_Txn_Date as date) as Policy_Txn_Date,
    cast(Policy_Txn_Post_Date as date) as Policy_Txn_Post_Date
from 
    MARTDB.dbo.stg_MFCPremiums_Prepare

1 个答案:

答案 0 :(得分:0)

将日期转换为varchar()和日期格式112,然后尝试转换为datetime

select 'NLFMF' as Source_code 
    ,gPolicy_Number_static
    ,gPolicy_Number
    ,PolicyNumber as Policy_Number
    ,TransactionGroup
    ,TransactionType
    ,Txn_Amount
    ,convert(datetime, convert(nvarchar(10), Policy_Txn_Date, 112)) as Policy_Txn_Date
    ,convert(datetime,  convert(nvarchar(10), Policy_Txn_Post_Date, 112)) as Policy_Txn_Post_Date
from MARTDB.dbo.stg_MFCPremiums_Prepare

DEMO