将 varchar 数据类型转换为 datetime 数据类型导致值超出范围 [英] conversion of a varchar data type to a datetime data type resulted in an out-of-range value

查看:110
本文介绍了将 varchar 数据类型转换为 datetime 数据类型导致值超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一段从 C# windows 服务运行的内联 SQL:

I have the following piece of inline SQL that I run from a C# windows service:

UPDATE table_name SET 
    status_cd = '2', 
    sdate = CAST('03/28/2011 18:03:40' AS DATETIME), 
    bat_id = '33acff9b-e2b4-410e-baaf-417656e3c255', 
    cnt = 1, 
    attempt_date = CAST('03/28/2011 18:03:40' AS DATETIME) 
WHERE id = '1855'

当我从应用程序中针对 SQL Server 数据库运行此程序时,出现以下错误:

When I run this against a SQL Server database from within the application, I get the following error:

System.Data.SqlClient.SqlException:将 varchar 数据类型转换为 datetime 数据类型导致值超出范围.声明已终止.

System.Data.SqlClient.SqlException: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

但是,如果我使用 SQL 的一部分并从 SQL Management Studio 运行它,它将毫无问题地运行.

But if I take the piece of SQL and run it from SQL Management Studio, it will run without issue.

任何想法可能导致此问题?

Any ideas what may be causing this issue?

推荐答案

不明确的日期格式根据登录语言进行解释.这有效

Ambiguous date formats are interpreted according to the language of the login. This works

set dateformat mdy

select CAST('03/28/2011 18:03:40' AS DATETIME)

这没有

set dateformat dmy

select CAST('03/28/2011 18:03:40' AS DATETIME)

如果您使用具有正确数据类型的参数化查询,则可以避免这些问题.您还可以使用明确未分隔"格式yyyyMMdd hh:mm:ss

If you use parameterised queries with the correct datatype you avoid these issues. You can also use the unambiguous "unseparated" format yyyyMMdd hh:mm:ss

这篇关于将 varchar 数据类型转换为 datetime 数据类型导致值超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆