简体   繁体   English

日期类型的列,并在其中插入值

[英]Column of Date type and inserting value into it

Hi I created a table in which one column is of date type and also works as PK . 嗨,我创建了一个表,其中一列是date类型,也可以用作PK I tried to insert value 2009-01-07 into this column and had this error. 我试图将值2009-01-07插入此列,并出现此错误。 Isn't Date default format yyyy-mm-dd ? 日期不是默认格式yyyy-mm-dd吗? I don't understand this. 我不明白

Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.

This is my query: 这是我的查询:

INSERT INTO Table_Name
Values ('2009-01-07', other column values)

Your value '2009-01-07' should be converted. 您的值'2009-01-07'应进行转换。

Date literals are always a deep source of troubles... Best was, to use either 日期字面量始终是造成麻烦的深层原因。

  • Unseparated: 20090107 不分隔:20090107
  • ODBC : {d'2009-01-07'} ODBC:{d'2009-01-07'}
  • ISO8601 : 2009-01-07T00:00:00 ISO8601:2009-01-07T00:00:00

But your format is short ISO 8601 and should work... 但是您的格式是简短的ISO 8601 ,应该可以...

Some possible reasons: 一些可能的原因:

  • Other values in your VALUES list 您的“ VALUES列表中的其他值
  • a trigger 扳机
  • a constraint 约束
  • As a_horse_with_no_name stated in comment: Without a column list after INSERT INTO Table(col1, col2, ...) There is a great risk to state your values in a different order thus pairing values with the wrong columns... a_horse_with_no_name注释中所述:在INSERT INTO Table(col1, col2, ...)之后没有列列表INSERT INTO Table(col1, col2, ...)存在很大的风险以不同的顺序声明您的值,从而将值与错误的列配对...
  • Invalid (but good looking ) dates such as 2016-06-31 无效(但好看 )的日期,例如2016-06-31

Or a - well known - issue with SQL-Server. 还是SQL Server的一个众所周知的问题。 Sometimes the order of execution is absolutely not the way one expected it. 有时执行顺序绝对不是人们期望的那样。 There are several issues with conversion errors... 转换错误有几个问题...

What you can try 你可以尝试什么

  • Use ODBC format (which is treated as DATETIME immediately) 使用ODBC格式(立即被视为DATETIME
  • DECLARE a variable with this value and put it in place 使用此值声明一个变量并将其放置到位

Thank you all for the prompt replies. 谢谢大家的及时答复。 I read and tried all of them and found out why. 我阅读并尝试了所有这些方法,并找出了原因。

  1. '2009-01-07' can be inserted into a Column with "Date" as data type if no CONSTRAINT has issue with that; 如果没有CONSTRAINT的问题,可以将“ 2009-01-07”插入到以“日期”作为数据类型的列中;
  2. my problem was caused by a CHECK constraint on that column. 我的问题是由该列上的CHECK约束引起的。 Originally I set CONSTRAINT as Column_Name = 'Wednesday' After I modified it to DATEName(dw,[Column_Name]) = 'Wednesday' the inserting began to work. 最初,我将CONSTRAINT设置为Column_Name ='Wednesday',在将其修改为DATEName(dw,[Column_Name])='Wednesday'之后,插入开始起作用。

Thanks again. 再次感谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM