Change a Nullable column to NOT NULL with Default Value

后端 未结 5 701
臣服心动
臣服心动 2021-02-02 05:17

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 constrai

相关标签:
5条回答
  • 2021-02-02 05:24

    you need to execute two queries:

    One - to add the default value to the column required

    ALTER TABLE 'Table_Name` ADD DEFAULT 'value' FOR 'Column_Name'

    i want add default value to Column IsDeleted as below:

    Example: ALTER TABLE [dbo].[Employees] ADD Default 0 for IsDeleted

    Two - to alter the column value nullable to not null

    ALTER TABLE 'table_name' ALTER COLUMN 'column_name' 'data_type' NOT NULL

    i want to make the column IsDeleted as not null

    ALTER TABLE [dbo].[Employees] Alter Column IsDeleted BIT NOT NULL

    0 讨论(0)
  • 2021-02-02 05:34

    I think you will need to do this as three 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
    
    UPDATE MyTable SET Created = GetDate() where Created IS NULL
    
    ALTER TABLE dbo.MyTable 
    ALTER COLUMN Created DATETIME NOT NULL 
    
    0 讨论(0)
  • 2021-02-02 05:35

    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 is NULL
    
    0 讨论(0)
  • 2021-02-02 05:41

    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
    
    0 讨论(0)
  • 2021-02-02 05:48

    Try this

    ALTER TABLE table_name ALTER COLUMN col_name data_type NOT NULL;

    0 讨论(0)
提交回复
热议问题