tags:

views:

37

answers:

3

Hello everyone,

I have a mysql table called pollOfTheWeek. It has a column "pollDate" of type date. I have two questions regarding this : 1. I declared the column while creating the table as [pollDate date] What I wanted is that this column be set automatically, when the user doesnt enter any value for this column. How do i declare the column to achieve this?

  1. Assuming that I have the same declaration as above, how do I enter an empty value. I mean if the column was of type varchar, I would enter empty value as " ". But since it is of type date, I get error when I enter the value as " ". How do I enter empty value for the pollDate column?
+1  A: 

there is no way to automatically set a DATE column to the current date/time in mysql. TIMESTAMPs can be automatically set to the current time though. alternatively, just pass NOW() as a parameter when you insert :

INSERT INTO pollOfTheWeek (name, pollDate) VALUES ('someName', NOW());

as to your other question, you probably want to allow NULL values in the date column and set them to NULL when there is no date given.

oedo
Yes, there is - DEFAULT constraints.
OMG Ponies
using a default of NOW() does not work with DATE columns. you cannot use a function or an expression as the default value for any type of column, except for the TIMESTAMP data type column, for which you can specify the CURRENT_TIMESTAMP as the default. see google for details :)
oedo
+2  A: 

You need to create a trigger:

CREATE TRIGGER triggerName
BEFORE INSERT ON yourTable
FOR EACH ROW
SET NEW.date = coalesce(NEW.date, curdate());

The empty value would be null.

klausbyskov
+1 for using COALESCE to keep manually inserted values
Álvaro G. Vicario
+1  A: 

MySQL has an extremely limited support for default values. In general, it must be a constant expression like '0' or '(none)' and functions are not allowed. The only exception I'm aware of is that you can set CURRENT_TIMESTAMP as default value for a TIMESTAMP column; however, this is not available for DATE or DATETIME columns. Unluckily, TIMESTAMP has a smaller range and contains time information.

So your options are:

  1. Do it in your client application by setting NOW() as value in your inserts.
  2. Write a trigger:

.

CREATE TRIGGER pollOfTheWeek_trg BEFORE INSERT ON pollOfTheWeek 
    FOR EACH ROW SET NEW.pollDate = NOW();

As about empty values, I would simply use NULL. Why use empty strings?

Álvaro G. Vicario