views:

48

answers:

2

I have a table which I want to record the timestamp of every order at every insertion time. However, I'm getting zero values for the timestamps.

Here's my schema:

CREATE TABLE IF NOT EXISTS orders(
            order_no VARCHAR(16) NOT NULL,
            volunteer_id VARCHAR(16) NOT NULL,
            date TIMESTAMP DEFAULT NOW(),
            PRIMARY KEY (order_no),
            FOREIGN KEY (volunteer_id) REFERENCES volunteer(id)
            ON UPDATE CASCADE ON DELETE CASCADE)
+2  A: 

"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"

Source: http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html

You are going to have to name the column in your insert query and pass Now() as value.

Fabian
You left out the most useful bit, didn't you? "The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column. See Section 10.3.1.1, “TIMESTAMP Properties” (http://dev.mysql.com/doc/refman/5.1/en/timestamp.html)."
T.J. Crowder
+1 @T.K. Crowder, must have missed that one ..., thanks!
Fabian
+2  A: 

Make sure you are not inserting rows with an empty date:

INSERT INTO orders VALUES (1, 1, '');

The above would insert an 0000-00-00 00:00:00 date.


The following works as expected in MySQL 5.0.51a:

CREATE TABLE IF NOT EXISTS orders(
            order_no VARCHAR(16) NOT NULL,
            volunteer_id VARCHAR(16) NOT NULL,
            date TIMESTAMP DEFAULT NOW(),
            PRIMARY KEY (order_no));

INSERT INTO orders (order_no, volunteer_id) VALUES (1, 1);
INSERT INTO orders (order_no, volunteer_id) VALUES (2, 1);
INSERT INTO orders (order_no, volunteer_id) VALUES (3, 1);
INSERT INTO orders (order_no, volunteer_id) VALUES (4, 1);

SELECT * FROM orders;

+----------+--------------+---------------------+
| order_no | volunteer_id | date                |
+----------+--------------+---------------------+
| 1        | 1            | 2010-03-29 17:10:37 |
| 2        | 1            | 2010-03-29 17:10:40 |
| 3        | 1            | 2010-03-29 17:10:44 |
| 4        | 1            | 2010-03-29 17:10:48 |
+----------+--------------+---------------------+
4 rows in set (0.00 sec)
Daniel Vassallo