Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a DateTime field in a database automatic?

I'm putting together a simple test database to learn MVC with. I want to add a DateTime field to show when the record was CREATED.

ID = int Name = Char DateCreated = (dateTime, DateTime2..?) 

I have a feeling that this type of DateTime capture can be done automatically - but that's all I have, a feeling. Can it be done? And if so how?

While we're on the subject: if I wanted to include another field that captured the DateTime of when the record was LAST UPDATED how would I do that.

I'm hoping to not do this manually.

like image 731
RocketGoal Avatar asked Mar 16 '10 16:03

RocketGoal


People also ask

How do I auto populate a date in MySQL?

You can use now() with default auto fill and current date and time for this. Later, you can extract the date part using date() function. Let us set the default value with some date.

What is the best way to store datetime in database?

In SQL Server it is best to store DataTime as one field. If you create an index on DataTime column it can be used as Date search and as DateTime search. Therefore if you need to limit all records that exist for the specific date, you can still use the index without having to do anything special.

How do I create a date field from a table in SQL Server?

You don't need to specify the format in the table definition as dates are stored in a binary format. CREATE TABLE APP( ID INT NOT NULL, DT DATE, ADDRESS NVARCHAR (100) , PRIMARY KEY (ID) ); When you try to insert into that table however, the server will try to convert the string to a date before inserting it.


1 Answers

You need to set the "default value" for the date field to getdate(). Any records inserted into the table will automatically have the insertion date as their value for this field.

The location of the "default value" property is dependent on the version of SQL Server Express you are running, but it should be visible in the column properties tab if you select the date field of your table when editing the table.

like image 183
Ant Avatar answered Sep 25 '22 23:09

Ant