Can I add a not null column without DEFAULT value

后端 未结 10 1518
Happy的楠姐
Happy的楠姐 2020-12-13 07:56

Can I add a column which is I specify as NOT NULL,I don\'t want to specify the DEFAULT value but MS-SQL 2005 says:

ALTER TABLE only allows columns to

相关标签:
10条回答
  • 2020-12-13 08:31

    Add the column to the table, update the existing rows so none of them are null, and then add a "not null" constraint.

    0 讨论(0)
  • 2020-12-13 08:34

    I used below approach it worked for me

    Syntax:
    ALTER TABLE <YourTable> ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>
    
    Example:
    ALTER TABLE Tablename ADD ColumnName datetime NOT NULL DEFAULT GETDATE();
    
    0 讨论(0)
  • 2020-12-13 08:35

    No you cannot. But you can consider to specify the default value to ('')

    0 讨论(0)
  • 2020-12-13 08:37

    I use this approach to insert NOT NULL column without default value

    ALTER TABLE [Table] ADD [Column] INT NULL
    GO
    UPDATE [Table] SET [Column] = <default_value>
    ALTER TABLE [Table] ALTER COLUMN [Column] INT NOT NULL
    
    0 讨论(0)
  • 2020-12-13 08:39

    No, you can't.

    Because if you could, SQL wouldn't know what to put as value in the already existing records. If you didn't have any records in the table it would work without issues.

    The simplest way to do this is create the column with a default and then remove the default.

    ALTER TABLE dbo.MyTable ADD
    MyColumn text NOT NULL CONSTRAINT DF_MyTable_MyColumn DEFAULT 'defaultValue'
    ALTER TABLE dbo.MyTable
    DROP CONSTRAINT DF_MyTable_MyColumn
    

    Another alternative would be to add the column without the constraint, fill the values for all cells and add the constraint.

    0 讨论(0)
  • 2020-12-13 08:44

    No - SQL Server quite reasonably rejects this, because it wouldn't know what value existing rows should have

    It's easy to create a DEFAULT at the same time, and then immediately drop it.

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