altering DEFAULT constraint on column SQL

前端 未结 3 2038
死守一世寂寞
死守一世寂寞 2020-12-11 07:19

I have an SQL script for creating a table, i would like the default of all but a few columns to be \"\" the others require a integer default of 0

The following crea

相关标签:
3条回答
  • 2020-12-11 07:26

    When you create a constraint without a name, the SQL Server automatically create internal name. It can be see in the [sys].[default_constraints].

    For example:

    DROP TABLE IF EXISTS [dbo].[StackOverflow];
    
    CREATE TABLE [dbo].[StackOverflow]
    (
        [colA] INT
       ,[colB] INT DEFAULT(0)
       ,[colC] CHAR(1) DEFAULT('x')
    );
    
    GO
    
    SELECT *
    FROM [sys].[default_constraints]
    WHERE [parent_object_id] = OBJECT_ID('[dbo].[StackOverflow]');
    
    GO
    

    You can use the name to drop the constraint.

    If you have more of them, you can use one of the scripts below:

    -- all suported editions
    DECLARE @DynamicTSQLStataement NVARCHAR(MAX)
           ,@TableNameWithSchema SYSNAME;
    
    SET @TableNameWithSchema = '[dbo].[StackOverflow]';
    
    SELECT @DynamicTSQLStataement = STUFF
    (
        (
            SELECT ';ALTER TABLE ' + @TableNameWithSchema + ' DROP CONSTRAINT ' + QUOTENAME([name])
            FROM [sys].[default_constraints]
            WHERE [parent_object_id] = OBJECT_ID('[dbo].[StackOverflow]')
            FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
        ,1
        ,1
        ,''
    );
    
    EXEC sp_executesql @DynamicTSQLStataement;
    
    GO
    

    or

    -- SQL Server 2016 or later
    
    DECLARE @DynamicTSQLStataement NVARCHAR(MAX)
           ,@TableNameWithSchema SYSNAME;
    
    SET @TableNameWithSchema = '[dbo].[StackOverflow]';
    
    SELECT @DynamicTSQLStataement = STRING_AGG('ALTER TABLE ' + @TableNameWithSchema + ' DROP CONSTRAINT ' + QUOTENAME([name]), ';')
    FROM [sys].[default_constraints]
    WHERE [parent_object_id] = OBJECT_ID('[dbo].[StackOverflow]');
    
    EXEC sp_executesql @DynamicTSQLStataement;
    
    GO
    
    0 讨论(0)
  • 2020-12-11 07:33

    When you add a default, you should use names for your constraints. This way you can later refer to those constraints by name.

    ALTER TABLE [dbo].[PMIPatients] ADD CONSTRAINT [PatientFallRiskLevel_Default] DEFAULT ((0)) FOR PatientFallRiskLevel
    

    Then you can drop it using:

    ALTER TABLE [dbo].[PMIPatients] DROP CONSTRAINT [PatientFallRiskLevel_Default] 
    
    0 讨论(0)
  • 2020-12-11 07:35

    The syntax is:

    ALTER TABLE [dbo].[PMIPatients] ADD CONSTRAINT NameYourConstraint DEFAULT ((0))  FOR [PatientFallRiskLevel]  
    
    ALTER TABLE [dbo].[PMIPatients] DROP CONSTRAINT NameYourConstraint 
    
    0 讨论(0)
提交回复
热议问题