What is correct syntax for an ALTER
statement to add a default value to an existing column?
I can add new column with no errors:
ALTER TABLE tb_TableName ADD Record_Status varchar(20)
But If I try to alter existing column to apply default value by using the following statement:
ALTER TABLE tb_TableName ALTER COLUMN Record_Status VARCHAR(20) NOT NULL DEFAULT ''
or
ALTER TABLE tb_TableName ALTER Record_Status VARCHAR(20) NOT NULL DEFAULT ''
I have get an error:
Incorrect syntax near 'Record_Status'.
Use SQL Server Management Studio Select the column for which you want to modify the data type. In the Column Properties tab, select the grid cell for the Data Type property and choose a new data type from the drop-down list. On the File menu, select Save table name.
Click the arrow next to the column that you want to change, and then select Column settings. In the menu, select the change that you want to make, such as formatting the column, moving left or right, hiding, or adding a column . The settings vary depending upon the type of column you are editing.
I think you want this syntax:
ALTER TABLE tb_TableName add constraint cnt_Record_Status Default '' for Record_Status
Based on some of your comments, I am going to guess that you might already have null
values in your table which is causing the alter of the column to not null
to fail. If that is the case, then you should run an UPDATE
first. Your script will be:
update tb_TableName set Record_Status = '' where Record_Status is null ALTER TABLE tb_TableName ALTER COLUMN Record_Status VARCHAR(20) NOT NULL ALTER TABLE tb_TableName ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status
See SQL Fiddle with demo
Try this one.
ALTER TABLE tb_TableName ALTER COLUMN Record_Status VARCHAR(20) NOT NULL ALTER TABLE tb_TableName ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With