Tuesday, May 25, 2010

How to add a default value to column in T-SQL (SQL Server)

If you have a Not Null column in SQL Server and you want have a default value you can add that at any time. The most difficult situation I have seen is doing it when you want the default to be the current date.

In the example below I have a table called Person and a column CreatedDateTimeUtc that I want to default to the current utc date if the value is null. This will occur on both update and insert.

ALTER TABLE [dbo].[Person] ADD  DEFAULT (GetUtcDate()) FOR [CreatedDateTimeUtc]

No comments: