views:

114

answers:

4

Hey everyone,

I came across an old table today with a datetime column called 'Created' which allows nulls. Now, I'd want to change this so that it is NOT NULL, and also include a constraint to add in a default value (getdate()).

So far I've got the following script, which works fine provided that i've cleaned up all the nulls beforehand:

ALTER TABLE dbo.MyTable ALTER COLUMN Created DATETIME NOT NULL 

Is there any way to also specify the default value as well on the ALTER statement?

+1  A: 

If its SQL Server you can do it on the column properties within design view

Try this?:

ALTER TABLE dbo.TableName ADD CONSTRAINT DF_TableName_ColumnName DEFAULT '01/01/2000' FOR ColumnName

BenW
This needs to be in script form so that it can be run as part of our automated release process.
Jim B
See Brians answer :)
BenW
Still no dice. The constraint gets added; but it still barfs when it tries to convert the NULL to NOT NULL
Jim B
Script to update all the nulls to set the value to your default then apply it? Sorry, ain't being much help!
BenW
+1  A: 

have you tried...

ALTER TABLE dbo.MyTable ALTER COLUMN Created DATETIME NOT NULL DEFAULT whatever;
Brian Hooper
Yeah; i gave that a shot, and it gives me the following error: Incorrect syntax near the keyword 'DEFAULT'.
Jim B
Oh. Sorry. Gave you a bum steer, then. Ought to work, though. It's standard SQL.
Brian Hooper
Are you sure it's Standard SQL? I had a quick look at the spec for SQL-92 and it seems the `SET` keyword is required before the `DEFAULT` keyword. Also, I'm not sure the data type/`NOT NULL` can be combined with the `DEFAULT` in the same `ALTER COLUMN` statement. Finally, Standard SQL doesn't have a `DATETIME` data type: what SQL Server calls `DATETIME` the Standard calls `TIMESTAMP` (and SQL Server uses `TIMESTAMP` to mean something else again!)
onedaywhen
Dear oh dear. Perhaps I don't know as much about this as I thought I did.
Brian Hooper
+4  A: 

I think you will need to do this as two separate statements. I've been looking around and everything i've seen seems to suggest you can do it if you are adding a column, but not if you are altering one.

ALTER TABLE dbo.MyTable
ADD CONSTRAINT my_Con DEFAULT GETDATE() for created

ALTER TABLE dbo.MyTable 
ALTER COLUMN Created DATETIME NOT NULL 
Abe Miessler
+1  A: 

You may have to first update all the records that are null to the default value then use the alter table statement.

Update dbo.TableName
Set
Created="01/01/2000"
where Created = NULL
Gage