从字符串错误转换到日期和/或时间的SQL

时间:2015-09-15 14:37:20

标签: sql sql-server vb.net tsql

这是我的表

CREATE TABLE [dbo].[RPost_Receipts]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [branch] [int] NULL,
    [policyref] [varchar](10) NULL,
    [receipt_email_received] [datetime] NULL,
    [receipt_email_to_openattach] [int] NULL,
    [receipt_email_to_openattach_dt] [datetime] NULL,
    [sender_name] [varchar](50) NULL,
    [sender_address] [varchar](100) NULL,
    [subject] [varchar](160) NULL,
    [message_id] [varchar](100) NULL,
    [time_received] [datetime] NULL,
    [delivery_to] [varchar](100) NULL,
    [delivery_status] [varchar](100) NULL,
    [delivery_report] [varchar](max) NULL,
    [delivery_time_utc] [datetime] NULL,
    [delivery_time_local] [datetime] NULL,
    [time_opened] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

这是我试图在同一个表上运行的以下UPDATE查询

UPDATE [FreshSystems].[dbo].[RPost_Receipts]
SET [sender_name] = 'RPost eSignOff Service' ,
    [sender_address] = 'contracts@usw.rpost.net' ,
    [subject] = 'Re: REF: 02-OGKX02PC01 Your Insurance Policy (2 of 2)' ,
    [message_id] = '49B918875098C1EFCB5A33FDB2D446FF5C294ACE' ,
    [time_received] = '9/15/2015 10:36:29 AM' ,
    [delivery_to] = 'AutoSaintCS@Fresh.co.uk' ,
    [delivery_status] = 'Delivered to Mailserver' ,
    [delivery_report] = '250 OK id=1ZbnbS-0003fY-4y engine03-30179-2.icritical.com (192.162.216.4)' ,
    [delivery_time_utc] = '9/15/2015 10:36:47 AM' ,
    [delivery_time_local] = '9/15/2015 10:36:47 AM' ,
    [time_opened] = 'NULL'
WHERE [branch] = 02
  AND [policyref] = 'OGKX02PC01'
  AND [delivery_to] IS NULL

为什么我收到转换错误

  

Msg 241,Level 16,State 1,Line 1
  从字符串转换日期和/或时间时转换失败。

插入进入'DATETIME'列并且正在插入的日期时间都已正确格式化,有人可以为我解释这个吗?

更新

问题似乎只发生在我的VB.NET应用程序中。在SQL Server Management Studio中运行该语句时,没问题,当它在我的VB.NET中执行时,它会因为从字符到Datetime的对话而失败。

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

问题是您是否尝试将NULL放入time_opened字段。 (这是一个日期时间字段)

将其从[time_opened] = 'NULL'更改为[time_opened] = NULL

UPDATE  [FreshSystems].[dbo].[RPost_Receipts]
SET     [sender_name] = 'RPost eSignOff Service' ,
    [sender_address] = 'contracts@usw.rpost.net' ,
    [subject] = 'Re: REF: 02-OGKX02PC01 Your Insurance Policy (2 of 2)' ,
    [message_id] = '49B918875098C1EFCB5A33FDB2D446FF5C294ACE' ,
    [time_received] = '9/15/2015 10:36:29 AM' ,
    [delivery_to] = 'AutoSaintCS@Fresh.co.uk' ,
    [delivery_status] = 'Delivered to Mailserver' ,
    [delivery_report] = '250 OK id=1ZbnbS-0003fY-4y engine03-30179-2.icritical.com (192.162.216.4)' ,
    [delivery_time_utc] = '9/15/2015 10:36:47 AM' ,
    [delivery_time_local] = '9/15/2015 10:36:47 AM' ,
    [time_opened] = NULL
    WHERE   [branch] = 02
    AND [policyref] = 'OGKX02PC01'
    AND [delivery_to] IS NULL

答案 1 :(得分:0)

我认为日期时间格式是yy-mm-dd hh:mm:ss而不是9/15/2015 10:36:29 AM 在更新表之前转换它。