Victor
Victor

Reputation: 953

SQL Alter table default error

I am trying to modify an Integer field on existing table from nullable to non-nullable and adding default value to it.

    ALTER TABLE dbo.current_status  
ALTER COLUMN next_sign_id INT NOT NULL

This statement works, but this one doesn't:

    ALTER TABLE dbo.current_performance_status  
ALTER COLUMN next_sign_tp_id INT NOT NULL DEFAULT(0)

What is the problem here and how do I achieve both in one statement? I am using sql 2008.

Upvotes: 0

Views: 843

Answers (1)

Aaron Bertrand
Aaron Bertrand

Reputation: 280262

You have to do this in three statements (thanks @MartinSmith for the sanity check, who suggested WITH VALUES which isn't correct in this case but still reminded me that this table may not be empty):

ALTER TABLE dbo.current_performance_status 
  ADD CONSTRAINT df DEFAULT (0) FOR next_sign_id;

UPDATE dbo.current_performance_status 
 SET next_sign_id = 0
 WHERE next_sign_id IS NULL

ALTER TABLE dbo.current_performance_status
  ALTER COLUMN next_sign_id INT NOT NULL;

Upvotes: 2

Related Questions