SQL 默认情况下在sql datetime列中插入空/空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13934621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert null/empty value in sql datetime column by default
提问by Ozi Oz
How do I create a table in SQL server with the default DateTime as empty, not 1900-01-01 00:00:00.000
that I get?
如何在 SQL Server 中创建一个表,默认 DateTime 为空,而不是1900-01-01 00:00:00.000
我得到的?
I mean, if there is no value inserted, the default value should be null, empty, etc.
我的意思是,如果没有插入值,默认值应该是空、空等。
回答by Mahmoud Gamal
if there is no value inserted, the default value should be null,empty
如果没有插入值,则默认值应为 null,empty
In the table definition, make this datetime
column allows null, be not defining NOT NULL
:
在表定义中,使该datetime
列允许为空,而不是定义NOT NULL
:
...
DateTimeColumn DateTime,
...
I HAVE ALLOWED NULL VARIABLES THOUGH.
虽然我已经允许 NULL 变量。
Then , just insert NULL
in this column:
然后,只需NULL
在此列中插入:
INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);
Or, you can make use of the DEFAULTconstaints:
或者,您可以使用DEFAULT约束:
...
DateTimeColumn DateTime DEFAULT NULL,
...
Then you can ignore it completely in the INSERT
statement and it will be inserted withe the NULL
value:
然后你可以在INSERT
语句中完全忽略它,它会被插入NULL
值:
INSERT INTO Table(name, ...)
VALUES('foo bar', ..);
回答by silly
- define it like
your_field DATETIME NULL DEFAULT NULL
- dont insert a blank string, insert a NULL
INSERT INTO x(your_field)VALUES(NULL)
- 像这样定义
your_field DATETIME NULL DEFAULT NULL
- 不要插入空字符串,插入 NULL
INSERT INTO x(your_field)VALUES(NULL)
回答by Uberbot7147
Ozi, when you create a new datetime object as in datetime foo = new datetime(); foo is constructed with the time datetime.minvalue() in building a parameterized query, you could check to see if the values entered are equal to datetime.minvalue()
Ozi,当你像 datetime foo = new datetime(); 一样创建一个新的 datetime 对象时;foo 在构建参数化查询时使用时间 datetime.minvalue() 构造,您可以检查输入的值是否等于 datetime.minvalue()
-Just a side thought. seems you have things working.
- 只是一个侧面的想法。似乎你有工作。
回答by zDavid
I was having the same issue this morning. It appears that for a DATE or DATETIME field, an empty value cannot be inserted. I got around this by first checking for an empty value (mydate = "") and if it was empty setting mydate = "NULL" before insert.
今天早上我遇到了同样的问题。对于 DATE 或 DATETIME 字段,似乎无法插入空值。我通过首先检查空值(mydate =“”)以及在插入之前设置mydate =“NULL”是否为空来解决这个问题。
The DATE and DATETIME fields don't behave in the same way as VARCHAR fields.
DATE 和 DATETIME 字段的行为方式与 VARCHAR 字段不同。