Groups | Blog | Home
all groups > sql server new users > august 2006 >

sql server new users : Setting column default


Dan Guzman
8/27/2006 11:36:10 AM

In Transact-SQL, you can add a default constraint with ALTER TABLE like the
example below. I would expect the GUI tool's 'Default Value' is the same
thing but I don't know for sure because I don't tool you are using.

ALTER TABLE dbo.MyTable
ADD CONSTRAINT DF_MyDateColumn
DEFAULT GETDATE() FOR MyDateColumn

--
Hope this helps.

Dan Guzman
SQL Server MVP

[quoted text, click to view]

Dan Guzman
8/27/2006 12:13:56 PM
Default constraint values apply only when the column is not included in the
insert statement. Conversely, if the INSERT statement explicitly specifies
NULL, a NULL is inserted instead of the default value. Is this your
situation?

--
Hope this helps.

Dan Guzman
SQL Server MVP

[quoted text, click to view]

Dan Guzman
8/27/2006 1:11:13 PM
SSMS is probably generating an INSERT statement with all columns and an
explicit NULL value. You can verify this with a Profiler Trace.

If you want the column value to always be GETDATE(), you can override the
value specified on the INSERT statement with an UPDATE in an insert trigger.
This will effectively ignore the inserted value.

--
Hope this helps.

Dan Guzman
SQL Server MVP

[quoted text, click to view]

Dan Guzman
8/27/2006 1:20:32 PM
BTW, I forgot to mention that the default value will also be inserted when
the keyword default is specified as the inserted value.

--
Hope this helps.

Dan Guzman
SQL Server MVP

[quoted text, click to view]

John
8/27/2006 5:15:41 PM
Hi

How can I make a datetime to default to current date/time? Can I set the
'Default Value or Binding' property to something to achieve that?

Thanks

Regards

John
8/27/2006 5:48:22 PM
Tried that but when I manually add a record to the table the column remains
null i.e. it does not default to current date/time.

Regards

[quoted text, click to view]

John
8/27/2006 6:56:04 PM
Well I just opened the table in management studio and typed a record into
the grid provided. I am assuming the management studio is using an insert
with all columns to handle this so date/time did not come up. Any way to
default the column to date/time regardless of what method of insertion is
used, even if it means that field becomes read only?

Thanks

Regards

[quoted text, click to view]

AddThis Social Bookmark Button