I have the table defined like this:
CREATE TABLE tt (
name varchar(255) DEFAULT NULL,
date timestamp NULL DEFAULT NULL
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;
Now I'm trying to insert a record:
INSERT INTO tt (name, date) VALUES('some', UNIX_TIMESTAMP(now()));
And get the following error:
Incorrect datetime value: '1428306271' for column 'date' at row 1
How can that be?
EDIT:
This option also produces an error:
INSERT INTO tt (name, date) VALUES('some', UNIX_TIMESTAMP());
The correct syntax would be
INSERT INTO tt (name, date) VALUES('some', now());
date timestamp NULL DEFAULT NULL will accept the values as
yyyy-mm-dd H:i:s
If you want to have current date time in field in format 2015-04-06 13:24:42,you should not require to add this field to query as it will automatically update current date time value in this format to database.
So your query will be : INSERT INTO tt (name) VALUES('some');
suppose current date time is 2015-04-06 13:24:42 so this will automatically updated to you date field ind database.
It will be as per UTC time.
TO_TIMESTAMP is the function to convert epoch to timestamp
INSERT INTO mytable (name, time) VALUES ('Hello', TO_TIMESTAMP(123))
Related
I'm trying to change the format of a date from a CSV file before insert. I created a trigger BEFORE INSERT but it doesn't seem to work.
CREATE TABLE items (
item_id int(11) NOT NULL AUTO_INCREMENT,
price_list_id int(11) NOT NULL,
sku varchar(20) NOT NULL,
description varchar(45) DEFAULT NULL,
cost float NOT NULL DEFAULT '0',
notes varchar(45) DEFAULT NULL,
discount_factor float DEFAULT '1',
start_date date DEFAULT NULL,
end_date date DEFAULT NULL,
PRIMARY KEY (item_id,sku),
KEY price_list_id_idx (price_list_id),
CONSTRAINT price_list_id FOREIGN KEY (price_list_id) REFERENCES price_lists (price_list_id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=105193 DEFAULT CHARSET=utf8;
This is my trigger BEFORE INSERT
CREATE TRIGGER `pricelist`.`items_BEFORE_INSERT` BEFORE INSERT ON `items` FOR EACH ROW
BEGIN
SET NEW.start_date = str_to_date(NEW.start_date, '%c/%e/%Y');
SET NEW.end_date = str_to_date(NEW.end_date, '%c/%e/%Y');
END
Let say the query is : INSERT IGNORE INTO pricelist.items (price_list_id, sku, description, cost, start_date, end_date, notes) VALUES ('15', '2494-22', 'M12 DRILL/IMPACT COMBO KIT', '129', '4/25/2016', '5/31/2016', 'CL6204');
I get this error :
`Error Code: 1411. Incorrect datetime value: '0000-00-00' for function str_to_date`
If i do (without IGNORE):
INSERT INTO pricelist.items (price_list_id, sku, description, cost, start_date, end_date, notes) VALUES ('15', '2494-22', 'M12 DRILL/IMPACT COMBO KIT', '129', '4/25/2016', '5/31/2016', 'CL6204');
I get this :
Error Code: 1292. Incorrect date value: '4/25/2016' for column 'start_date' at row 1
Although this works :
SELECT str_to_date('5/31/2016', '%c/%e/%Y');
The output is :
2016-05-31
Any help would be appreciated! Thanks.
You are gettting this error because you are trying to insert a date column which is of the wrong format. The MySQL documentation lists the formats which are acceptable:
MySQL recognizes DATE values in these formats:
As a string in either 'YYYY-MM-DD' or 'YY-MM-DD' format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example, '2012-12-31', '2012/12/31', '2012^12^31', and '2012#12#31' are equivalent.
As a string with no delimiters in either 'YYYYMMDD' or 'YYMMDD' format, provided that the string makes sense as a date.
As a number in either YYYYMMDD or YYMMDD format, provided that the number makes sense as a date.
But your date has the format MM/DD/YYYY, e.g. 4/25/2016, so this won't work. It appears you were attempting to use a trigger to correct the format before the insert. However, MySQL checks the formatting before the trigger is even hit.
If you must insert date data with this format then you should do so using a VARCHAR type and then call STR_TO_DATE afterwards. Or, you should clean up the formatting of your dates to match one of the acceptable formats.
I have a table called 'products' with some columns. One of them is called 'date' and should contain the date on which the product was added as Unix time stamp. Normally I would use the NOW() function but since the value needs to be an integer and I can't cast the NOW() function as integer, I need to find another way. Any ideas ?
Modify the column to be of type TIMESTAMP and set it's default value (if you want to set the column to the date it was added on) to CURRENT_TIMESTAMP.
ALTER TABLE `products` MODIFY `date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
TIMESTAMP is not a string but an integer timestamp, it is just displayed as a string and you can use operators on it.
With DEFAULT CURRENT_TIMESTAMP you don't need to insert the date, mysql will do it for you.
MySQL has a function with the surprising name unix_timestamp:
INSERT INTO `products`
(`name`, `date`)
VALUES ('some name', UNIX_TIMESTAMP())
If I create a table with an entity that is suppose to be DATE and when I Insert and leave that column blank shouldn't it display the current date? Same with time?
For example...
CREATE TABLE Register
(
Name CHAR(20) NOT NULL,
Date DATE,
Time TIME
);
Then I Insert:
INSERT INTO Register (Name)
VALUES ('Howard');
I want it to display on the table:
Howard | 5/6/2014 | 8:30 PM
But instead it displays:
Howard | NULL | NULL
Is this incorrect and if so what am I suppose to Insert to allow the current date and time of insert to display?
Firstly, you should have a PRIMARY KEY in your table.
Secondly, you have not set default values for columns Date and Time. Also, you can't set them separately for the DATE and TIME types – you should use TIMESTAMP type and DEFAULT CURRENT_TIMESTAMP like :
CREATE TABLE Register (
Name CHAR(20) PRIMARY KEY NOT NULL,
Date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Thirdly, if you want to use exactly two columns for date storing, you can set a trigger on INSERT event for this table, like it is shown below :
CREATE TRIGGER default_date_time
BEFORE INSERT ON my_table_name
FOR EACH ROW
BEGIN
SET NEW.Date = CURDATE();
SET NEW.Time = CURTIME();
END;
$$
You need to set a default. So you might think you could do this:
CREATE TABLE Register
(
Name CHAR(20) NOT NULL,
Date DATE DEFAULT CURRENT_DATE,
Time TIME DEFAULT CURRENT_TIME
);
But that won’t work. You need to use CURRENT_TIMESTAMP and change your DB structure to use the combined TIMESTAMP format:
CREATE TABLE Register
(
Name CHAR(20) NOT NULL,
Timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
The reason being is there is no MySQL DEFAULT value for DATE or TIME alone. Some clues to that behavior here:
The DEFAULT value clause in a data type specification indicates a
default value for a column. With one exception, the default value must
be a constant; it cannot be a function or an expression. This means,
for example, that you cannot set the default for a date column to be
the value of a function such as NOW() or CURRENT_DATE. The exception
is that you can specify CURRENT_TIMESTAMP as the default for a
TIMESTAMP column. See Section 11.3.5, “Automatic Initialization and
Updating for TIMESTAMP”.
Here are two options:
Get rid of Date and Time columns and add time stamp
INSERT INTO Register (Name,Ctime) VALUES ('Howard',CURRENT_TIMESTAMP);
If you want to continue with your table structure
INSERT INTO Register (Name,Date,Time) VALUES ('Howard',CURDATE(), CURTIME());
Also Note that date and time are reserved words of MySQL and hence should be quoted with backticks to avoid conflicting with reserved words. Or just rename it according to a table name format.
I think I may have encountered a bug in mysql, or is it just me doing it wrong.
I've been using the same specific queries for the last four months and just today it stopped working somehow. I can't see the problem.
I'm executing these queries in the mysql console it works great, and the field is being updated. but when these queries are being executed by PHP it fails.
After insertion of a record into a table(with two timestamp fields), I'm trying to update a specific timestamp column.
But unfortunately it fails to update the column.
The query goes well(no errors), but still the value in the timestamp column stays the same. That's weird, cause when I'm leaving the initial column value as NULL, the update query succeed.
Columns :
START_DATETIME, END_DATETIME - are "timestamp" type.
Insert:
INSERT INTO TABLE1(START_DATETIME, END_DATETIME, RESPONSE)
VALUES(NOW(), NOW(), 'STARTED')
Insert is done successfully. id is 123
The update query is normal like any other query:
UPDATE TABLE1
SET END_DATETIME = NOW(), RESPONSE='ENDED'
WHERE ID = 123
Update fails, END_DATETIME doesn't get the NOW() value.
Can be reproduced with this:
CREATE TABLE TABLE1
(
id int auto_increment,
start_datetime timestamp,
end_datetime timestamp,
response varchar(100),
primary key(id)
);
You probably have defined the first timestamp column (the START_DATETIME one) to be auto-inserted and auto-updated with the CURRENT_TIMESTAMP value (which is the same as NOW().
Notice that if you don't explicitedly state anything about the TIMESTAMP columns in the CREATE TABLE script, the first one of them gets by default this behaviour/attributes. Read the MySQL documentation about this Automatic Initialization and Updating for TIMESTAMP, where it states:
With neither DEFAULT CURRENT_TIMESTAMP nor ON UPDATE CURRENT_TIMESTAMP, it is the same as specifying both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP.
So, if you do a SHOW CREATE TABLE tableName, you'll have something like this:
CREATE TABLE table1
( ...
, START_DATETIME TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
, ...
) ;
You should alter the column definition to not be auto_updated, if you don't want this behaviour:
ALTER TABLE table1
MODIFY COLUMN
START_DATETIME TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP ;
After looking into this more this is what I'd expect if the first table has ON UPDATE CURRENT_TIMESTAMP as it is being automatically set by the update to the second record.
I don't think that this can have been working previously;
to fix it:
ALTER TABLE TABLE1
CHANGE COLUMN start_datetime start_datetime TIMESTAMP NULL DEFAULT NULL AFTER id,
CHANGE COLUMN end_datetime end_datetime TIMESTAMP NULL DEFAULT NULL AFTER start_datetime;
If you want date time values the TIMESTAMP isn't much good for this as it is useful for auto-updating values as the TIMESTAMP data type offers automatic initialization and updating to the current date and time. For more information, see Automatic Initialization and Updating for TIMESTAMP
If you need a field you can manage yourself then one of the other types
DATE
DATETIME
may be more appropriate, see 11.3.1. The DATE, DATETIME, and TIMESTAMP Types
This is a problem with timestamp type, If you change both the column to datetime, you will get what you are expecting
I have three *date fields in a table defined as VARCHAR(45) with a default value of '00-00-0000'. Each of the fields needs the default value of the current system time when a record is created.
I have changed one of the fields from VARCHAR(45) to TIMESTAMP with default of CURRENT_TIMESTAMP, which works great. I think I can only have a single field with Datatype TIMESTAMP per table.
How do I handle the other 2 fields in the tables? I would like to *CURRENT_TIMESTAMP them too.
Thanks
Use the NOW() function:
INSERT INTO yourtable (field1, field2) VALUES ('blahblah', now());
You can use "NOW()" in a MySQL query to fill in the current time for a timestamp column.
You can write Now() to the fields
INSERT INTO table (right_now)
VALUES (Now()):