Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 fill the datetime automatically

Author  Topic 

allan8964
Posting Yak Master

249 Posts

Posted - 2012-02-16 : 14:10:37
Hi there,

Is it possible to automatically fill a datetime typed field? Like this table:

ID | Name | FillDate | ...
11 | John | 12/02/2012 |
...

I want the field FillDate automatically filled with current date time when the record saved. Thanks in advance.

russell
Pyro-ma-ni-yak

5072 Posts

Posted - 2012-02-16 : 14:20:44
Create Table YourTable (
ID int,
Name Varchar(32),
FillDate datetime NOT NULL DEFAULT getdate()
)
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2012-02-16 : 14:21:20
[code]

CREATE TABLE myTable99(ID int, Name varchar(50), FillDate datetime)
GO

INSERT INTO myTable99(ID, Name, FillDate)
SELECT 11, 'John', '12/02/2012'
GO

SELECT * FROM myTable99
GO

ALTER TABLE myTable99 ADD CONSTRAINT DEF_myTable99_FillDate_GetDate DEFAULT (GetDate()) FOR FillDate
GO

INSERT INTO myTable99(ID, Name)
SELECT 12, 'Brett'
GO

SELECT * FROM myTable99
GO

DROP TABLE myTable99
GO

[/code]


Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-02-16 : 15:37:54
Please keep in mind that creating a default like in previous suggestions will auto populate values only for new inserts. If you want current date value to be captured even for update operations as well, you might need a separate trigger for that.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

allan8964
Posting Yak Master

249 Posts

Posted - 2012-02-17 : 17:16:27
Thanks gents for the guide. Actually I noticed that the constraints not working with update, Yes I need to create a trigger for that.
Go to Top of Page
   

- Advertisement -