2011-02-10 50 views
0

在我搞乱我的数据库之前,我有一个快速的问题:SQL - 如何更换与其他日期时间日期时间价值?

什么是用另一个日期时间值替换datetime值的SQL命令?我会用“0000-00-00 00:00:00”,以取代所有日期时间在我的数据库表中的一列。

我猜的SQL命令是这样的命令,以取代在单个列/表?:所有字符串值

UPDATE table_name SET field_id = '0000-00-00 00:00:00' 

这是我第一次更换所有DateTime值这样的 - 是的,我已经做了一个数据库备份,以防万一!

+2

你已经有答案了,只要运行它。 – 2011-02-10 17:36:51

回答

1

的答案来对付乔的。总之,去了。另外,您不需要明确写出00:00:00。

drop table if exists testdt; 
create table testdt (dt datetime); 
insert testdt select curdate(); 

update testdt set dt = '0000-00-00'; 

select * from testdt; 

输出:

dt 
------------------- 
0000-00-00 00:00:00 

注:http://dev.mysql.com/doc/refman/5.0/en/date-and-time-types.html

MySQL也允许你将 '0000-00-00' 保存为“伪日期”(如果你不使用NO_ZERO_DATE SQL模式)。这在某些情况下比使用NULL值更方便(并且使用更少的数据和索引空间)。

如果您使用的“1000年1月1日”的valid range以外的日期为“9999-12-31”,MySQL的在其所有的智慧会让你存储它,甚至用它!

drop table if exists testdt; 
create table testdt (dt datetime); 

insert testdt select curdate(); 
update testdt set dt = '0000-00-00'; 

insert testdt select '0010-01-01'; 
insert testdt select '1010-01-01'; 
insert testdt select '1000-00-00'; 
insert testdt select '0000-01-01'; 
select *, adddate(dt, interval 999 year) from testdt; 

输出(无效的日期与月=天= 0不可用)

dt     adddate(dt, interval 999 year) 
0000-00-00 00:00:00 NULL 
0010-01-01 00:00:00 1009-01-01 00:00:00 
1010-01-01 00:00:00 2009-01-01 00:00:00 
1000-00-00 00:00:00 NULL 
0000-01-01 00:00:00 0999-01-01 00:00:00