Riho
Riho

Reputation: 4593

updating DATE fields

I inherited MYSQL database that has lots of tables with data like

CREATE TABLE IF NOT EXISTS `ejl_registration` (
  `id` int(11) NOT NULL auto_increment,
  `team_id` int(11) default NULL,
  `start_date` date default NULL,
  `end_date` date default NULL,
  PRIMARY KEY  (`id`),
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=88668 ;

start_date and end_date should have values like:

But some of those en_date fields are either NULL or 0000-00-00. Is there a ways to have single query to update all those invalid en_date fields and set their value to the end of the year equal to the year of start_date

Upvotes: 2

Views: 231

Answers (2)

MatBailie
MatBailie

Reputation: 86706

I don't know if DATEADD and DATEDIFF exist in MySQL, but I would strongly advise using some kind of date function rather than converting to strings and manipulating them that way.

In MS SQL SERVER this would work...

UPDATE
    ejl_registration
SET
    end_date = DATEADD(YEAR, 1 + DATEDIFF(YEAR, 0, start_date), 0)
WHERE
    (end_date) IS NULL OR (end_date = '0000-00-00')

Upvotes: 0

David Hanak
David Hanak

Reputation: 10974

Try this (please double check, I have not tested the command):

UPDATE `ejl_registration` SET `end_date`= CONCAT(YEAR(`start_date`),'-12-31')
WHERE `end_date` IS NULL OR `end_date` = '0000-00-00';

Upvotes: 3

Related Questions