Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter column in SQL Server

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'.

like image 946
GenZiy Avatar asked Nov 08 '12 17:11

GenZiy


People also ask

How do I change the properties of a column in SQL Server?

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.

How do you modify columns?

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.


2 Answers

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

like image 175
Taryn Avatar answered Sep 22 '22 07:09

Taryn


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 
like image 30
Prakash Avatar answered Sep 22 '22 07:09

Prakash