Making a DateTime field in a database automatic?
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.
Just right click on that column and select properties and write getdate()
in Default value or binding
.like image:
If you want do it in CodeFirst
in EF
you should add this attributes befor of your column definition:
[Databasegenerated(Databaseoption.computed)]
this attributes can found in System.ComponentModel.Dataannotion.Schema
.
Yes, here's an example:
CREATE TABLE myTable ( col1 int, createdDate datetime DEFAULT(getdate()), updatedDate datetime DEFAULT(getdate()) )
You can INSERT into the table without indicating the createdDate and updatedDate columns:
INSERT INTO myTable (col1) VALUES (1)
Or use the keyword DEFAULT:
INSERT INTO myTable (col1, createdDate, updatedDate) VALUES (1, DEFAULT, DEFAULT)
Then create a trigger for updating the updatedDate column:
CREATE TRIGGER dbo.updateMyTable
ON dbo.myTable
FOR UPDATE
AS
BEGIN
IF NOT UPDATE(updatedDate)
UPDATE dbo.myTable SET updatedDate=GETDATE()
WHERE col1 IN (SELECT col1 FROM inserted)
END
GO