Ошибка alter table drop column

I am trying to do this:

ALTER TABLE CompanyTransactions DROP COLUMN Created

But I get this:

Msg 5074, Level 16, State 1, Line 2
The object ‘DF__CompanyTr__Creat__0CDAE408’ is dependent on column ‘Created’.
Msg 4922, Level 16, State 9, Line 2
ALTER TABLE DROP COLUMN Created failed because one or more objects access this column.

This is a code first table. Somehow the migrations have become all messed up and I am trying to manually roll back some changed.

I have no idea what this is:

DF__CompanyTr__Creat__0CDAE408

asked Apr 21, 2017 at 18:11

Casey Crookston's user avatar

Casey CrookstonCasey Crookston

12.9k24 gold badges106 silver badges192 bronze badges

1

You must remove the constraints from the column before removing the column. The name you are referencing is a default constraint.

e.g.

alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];
alter table CompanyTransactions drop column [Created];

answered Apr 21, 2017 at 18:14

SqlZim's user avatar

4

The @SqlZim’s answer is correct but just to explain why this possibly have happened. I’ve had similar issue and this was caused by very innocent thing: adding default value to a column

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int DEFAULT NULL;

But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.

So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int NULL,
  CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;

You’ll still have to drop the constraint before dropping the column, but you will at least know its name up front.

answered Jan 30, 2018 at 19:13

malloc4k's user avatar

malloc4kmalloc4k

1,7043 gold badges22 silver badges22 bronze badges

1

As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.

Perform followings steps to do the needful.

  1. Get Name of all Constraints using sp_helpconstraint which is a system stored procedure utility — execute following exec sp_helpconstraint '<your table name>'
  2. Once you get the name of the constraint then copy that constraint name and execute next statement i.e alter table <your_table_name>
    drop constraint <constraint_name_that_you_copied_in_1>
    (It’ll be something like this only or similar format)
  3. Once you delete the constraint then you can delete 1 or more columns by using conventional method i.e Alter table <YourTableName> Drop column column1, column2 etc

answered Dec 27, 2018 at 10:34

vibs2006's user avatar

vibs2006vibs2006

5,9083 gold badges39 silver badges39 bronze badges

When you alter column datatype you need to change constraint key for every database

  alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];

Salman Zafar's user avatar

Salman Zafar

3,8164 gold badges20 silver badges43 bronze badges

answered Jul 4, 2019 at 6:46

Jayant Wexoz's user avatar

1

You need to do a few things:

  1. You first need to check if the constrain exits in the information schema
  2. then you need to query by joining the sys.default_constraints and sys.columns
    if the columns and default_constraints have the same object ids
  3. When you join in step 2, you would get the constraint name from default_constraints. You drop that constraint. Here is an example of one such drops I did.
-- 1. Remove constraint and drop column
IF EXISTS(SELECT *
          FROM INFORMATION_SCHEMA.COLUMNS
          WHERE TABLE_NAME = N'TABLE_NAME'
            AND COLUMN_NAME = N'LOWER_LIMIT')
   BEGIN
    DECLARE @sql NVARCHAR(MAX)
    WHILE 1=1
        BEGIN
            SELECT TOP 1 @sql = N'alter table [TABLE_NAME] drop constraint ['+dc.name+N']'
            FROM sys.default_constraints dc
            JOIN sys.columns c
            ON c.default_object_id = dc.object_id
            WHERE dc.parent_object_id = OBJECT_ID('[TABLE_NAME]') AND c.name = N'LOWER_LIMIT'
            IF @@ROWCOUNT = 0
                BEGIN
                    PRINT 'DELETED Constraint on column LOWER_LIMIT'
                    BREAK
                END
        EXEC (@sql)
    END;
    ALTER TABLE TABLE_NAME DROP COLUMN LOWER_LIMIT;
    PRINT 'DELETED column LOWER_LIMIT'
   END
ELSE
   PRINT 'Column LOWER_LIMIT does not exist'
GO

answered Aug 7, 2019 at 20:16

Akash Yellappa's user avatar

In addition to accepted answer, if you’re using Entity Migrations for updating database, you should add this line at the beggining of the Up() function in your migration file:

Sql("alter table dbo.CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];");

You can find the constraint name in the error at nuget packet manager console which starts with FK_dbo.

answered Oct 17, 2020 at 15:10

ninbit's user avatar

ninbitninbit

5306 silver badges24 bronze badges

I had the same problem and this was the script that worked for me with a table with a two part name separated by a period «.».

USE [DATABASENAME]
GO
ALTER TABLE [TableNamePart1].[TableNamePart2] DROP CONSTRAINT [DF__ TableNamePart1D__ColumnName__5AEE82B9]
GO
ALTER TABLE [TableNamePart1].[ TableNamePart1] DROP COLUMN [ColumnName]
GO

answered Nov 8, 2020 at 14:01

ConkrStuff's user avatar

I needed to replace an INT primary key with a Guid. After a few failed attempts, the EF code below worked for me. If you hyst set the defaultValue… you end up with a single Guid a the key for existing records.

protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropUniqueConstraint("PK_Payments", "Payments");

            migrationBuilder.DropColumn(
                name: "PaymentId",
                table: "Payments");

            migrationBuilder.AddColumn<Guid>(
                name: "PaymentId",
                table: "Payments",
                type: "uniqueidentifier",
                defaultValueSql: "NewId()",
                nullable: false);
}

answered Apr 24, 2021 at 6:56

Corey Jensen's user avatar

Copy the default constraint name from the error message and type it in the same way as the column you want to delete.

answered Mar 18, 2022 at 1:39

Anar Batbold's user avatar

1

I had the same problem, I could not remove migrations, it would show error that something is already applied, so i changed my DB name in appsettings, removed all migrations, and then added new migration and it worked. Dont understand issue completely, but it worked

answered Jan 17 at 14:42

Modestas Vacerskas's user avatar

I fixed by Adding Dropping constraint inside migration.

migrationBuilder.DropForeignKey(
         name: "FK_XX",
         table: "TableX").

and below recreates constraint.

migrationBuilder.AddForeignKey(
          name: "FK_XX",
          table: "TableX",
          column: "ColumnX",             
          onDelete: ReferentialAction.Restrict);

answered Feb 7 at 9:11

Zakarie Abdallah's user avatar

Я пытаюсь сделать это:

ALTER TABLE CompanyTransactions DROP COLUMN Created

Но я получаю это:

Msg 5074, уровень 16, состояние 1, строка 2 Объект «DF__CompanyTr__Creat__0CDAE408» зависит от столбца «Создано». Msg 4922, уровень 16, состояние 9, строка 2 ALTER TABLE DROP COLUMN Создан неудачно, потому что один или несколько объектов обращаются к этому столбцу.

Это первая таблица кода. Как-то миграции перепутались, и я пытаюсь вручную отменить некоторые измененные.

Я понятия не имею, что это такое:

DF__CompanyTr__Creat__0CDAE408

4b9b3361

Ответ 1

Вы должны удалить constraints из столбца перед удалением столбца. Имя, на которое вы ссылаетесь, — default constraint.

например.

alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];
alter table CompanyTransactions drop column [Created];

Ответ 2

Ответ @SqlZim верен, но только для того, чтобы объяснить, почему это произошло. У меня была аналогичная проблема, и это было вызвано очень невинной вещью: добавление значения по умолчанию в столбец

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int DEFAULT NULL;

Но в области MS SQL Server значением по умолчанию для colum является CONSTRAINT. И, как и каждое ограничение, он имеет идентификатор. И вы не можете удалить столбец, если он используется в CONSTRAINT.

Так что вы действительно можете избежать подобных проблем, всегда указывать ограничения по умолчанию явное имя, например:

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int NULL,
  CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;

Вам все равно придется отказаться от ограничения, прежде чем отбрасывать столбец, но вы по крайней мере знаете его имя спереди.

Ответ 3

Как уже написано в ответах, вам нужно удалить ограничения (созданные автоматически sql), относящиеся ко всем столбцам, которые вы пытаетесь удалить.

Выполните следующие шаги, чтобы сделать все необходимое.

  1. Получить имя всех ограничений, используя sp_helpconstraint, которая является системной утилитой хранимой процедуры — выполнить после exec sp_helpconstraint '<your table name>'
  2. Как только вы получите имя ограничения, скопируйте это имя ограничения и выполните следующую инструкцию, т. alter table <your_table_name> drop constraint <constraint_name_that_you_copied_in_1> (это будет что-то вроде этого только или подобный формат)
  3. После того как вы удалите ограничение, вы можете удалить 1 или более столбцов, используя обычный метод, т. Alter table <YourTableName> Drop column column1, column2 т.д.

Ответ 4

Вам нужно сделать несколько вещей:

  1. Сначала вам нужно проверить, выходит ли ограничение в информационной схеме
  2. тогда вам нужно сделать запрос, соединив sys.default_constraints и sys.columns
    если столбцы и default_constraints имеют одинаковые идентификаторы объектов
  3. Когда вы присоединитесь к шагу 2, вы получите имя ограничения из default_constraints. Вы отбрасываете это ограничение. Вот пример одной такой капли, которую я сделал.
-- 1. Remove constraint and drop column
IF EXISTS(SELECT *
          FROM INFORMATION_SCHEMA.COLUMNS
          WHERE TABLE_NAME = N'TABLE_NAME'
            AND COLUMN_NAME = N'LOWER_LIMIT')
   BEGIN
    DECLARE @sql NVARCHAR(MAX)
    WHILE 1=1
        BEGIN
            SELECT TOP 1 @sql = N'alter table [TABLE_NAME] drop constraint ['+dc.name+N']'
            FROM sys.default_constraints dc
            JOIN sys.columns c
            ON c.default_object_id = dc.object_id
            WHERE dc.parent_object_id = OBJECT_ID('[TABLE_NAME]') AND c.name = N'LOWER_LIMIT'
            IF @@ROWCOUNT = 0
                BEGIN
                    PRINT 'DELETED Constraint on column LOWER_LIMIT'
                    BREAK
                END
        EXEC (@sql)
    END;
    ALTER TABLE TABLE_NAME DROP COLUMN LOWER_LIMIT;
    PRINT 'DELETED column LOWER_LIMIT'
   END
ELSE
   PRINT 'Column LOWER_LIMIT does not exist'
GO

Ответ 5

Когда вы изменяете datatype столбца, вам нужно изменить constraint key для каждой базы данных

  alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];

  • Remove From My Forums
  • Question

  • I am trying to learn SQL Server; experimenting with some SQL. 
    I tried this

    USE Northwind

    ALTER
    TABLE Employees

    ADD

    DateOfBirth
    datetime NULL,

    LastRaiseDate
    datetime NOT
    NULL

    DEFAULT
    ‘2005-01-01’

    That worked fine! 
    Now, I am trying this:

    USE Northwind

    Alter
    Table Employees

    DROP
    Column DateOfBirth, LastRaiseDate

    I get this error message:

    Msg 5074, Level 16, State 1, Line 2

    The object ‘DF__Employees__LastR__4BAC3F29’ is dependent on column ‘LastRaiseDate’.

    Msg 4922, Level 16, State 9, Line 2

    ALTER TABLE DROP COLUMN LastRaiseDate failed because one or more objects access this column.

    I’m guessing that there is a Foreign Key constraint in place. 
    So, I went into Design Mode, deleted the Primary Key, saved the table, and reran the Alter-Drop SQL; results are the same. 
    There is something preventing me from dropping the two colums that I just added (quite easily). 
    What am I doing wrong?

Answers

  • hi,

    before dropping the column, you have to drop the constraint based on that column.. in your case the default constraint.. you did not name it at creation time, so the engine will propose and use a system generated name for that constraint, in your case ‘DF__Employees__LastR__4BAC3F29′

    so drop it and you can proceed, as trivialy indicated in the following sample,

    SET NOCOUNT ON;
    USE tempdb;
    GO
    CREATE TABLE dbo.test (
     Id int NOT NULL
     );
    GO
    ALTER TABLE dbo.test
     ADD LastRaiseDate datetime NOT NULL DEFAULT ‘2005-01-01’;
    GO
    PRINT ‘this will throw an exception as a default constraint is set for that column’;
    ALTER TABLE dbo.test
     DROP COLUMN LastRaiseDate;
    GO
    PRINT ‘take the default name of the default constraint and drop it’;
    ALTER TABLE dbo.test
     DROP CONSTRAINT DF__test__LastRaiseD__023D5A04;

    PRINT ‘now you can drop the column’;
    ALTER TABLE dbo.test
     DROP COLUMN LastRaiseDate;

     
    GO
    DROP TABLE dbo.test;

    regards


    http://www.asql.biz — DbaMgr2k — DbaMgr and further SQL Tools http://www.hotelsole.com/ — http://www.hotelsolericcione.de

    • Proposed as answer by

      Monday, July 18, 2011 11:13 PM

    • Marked as answer by
      ryguy72
      Wednesday, July 20, 2011 1:22 PM

  • >> wonder if there is a way for SQL Server to determine the Constraint automatically, or dynamically. 

    You can find out all constraint defined on a table using system stored procedure

    sp_helpconstraint

    in  your case EXEC sp_helpconstraint ‘Employees’;

    should list all constraint defined on that table.

    • Proposed as answer by
      Andrea Montanari
      Monday, July 18, 2011 11:22 PM
    • Marked as answer by
      ryguy72
      Wednesday, July 20, 2011 1:22 PM

Solution 1

You must remove the constraints from the column before removing the column. The name you are referencing is a default constraint.

e.g.

alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];
alter table CompanyTransactions drop column [Created];

Solution 2

The @SqlZim’s answer is correct but just to explain why this possibly have happened. I’ve had similar issue and this was caused by very innocent thing: adding default value to a column

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int DEFAULT NULL;

But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.

So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int NULL,
  CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;

You’ll still have to drop the constraint before dropping the column, but you will at least know its name up front.

Solution 3

As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.

Perform followings steps to do the needful.

  1. Get Name of all Constraints using sp_helpconstraint which is a system stored procedure utility — execute following exec sp_helpconstraint '<your table name>'
  2. Once you get the name of the constraint then copy that constraint name and execute next statement i.e alter table <your_table_name>
    drop constraint <constraint_name_that_you_copied_in_1>
    (It’ll be something like this only or similar format)
  3. Once you delete the constraint then you can delete 1 or more columns by using conventional method i.e Alter table <YourTableName> Drop column column1, column2 etc

Solution 4

When you alter column datatype you need to change constraint key for every database

  alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];

Solution 5

You need to do a few things:

  1. You first need to check if the constrain exits in the information schema
  2. then you need to query by joining the sys.default_constraints and sys.columns
    if the columns and default_constraints have the same object ids
  3. When you join in step 2, you would get the constraint name from default_constraints. You drop that constraint. Here is an example of one such drops I did.
-- 1. Remove constraint and drop column
IF EXISTS(SELECT *
          FROM INFORMATION_SCHEMA.COLUMNS
          WHERE TABLE_NAME = N'TABLE_NAME'
            AND COLUMN_NAME = N'LOWER_LIMIT')
   BEGIN
    DECLARE @sql NVARCHAR(MAX)
    WHILE 1=1
        BEGIN
            SELECT TOP 1 @sql = N'alter table [TABLE_NAME] drop constraint ['+dc.name+N']'
            FROM sys.default_constraints dc
            JOIN sys.columns c
            ON c.default_object_id = dc.object_id
            WHERE dc.parent_object_id = OBJECT_ID('[TABLE_NAME]') AND c.name = N'LOWER_LIMIT'
            IF @@ROWCOUNT = 0
                BEGIN
                    PRINT 'DELETED Constraint on column LOWER_LIMIT'
                    BREAK
                END
        EXEC (@sql)
    END;
    ALTER TABLE TABLE_NAME DROP COLUMN LOWER_LIMIT;
    PRINT 'DELETED column LOWER_LIMIT'
   END
ELSE
   PRINT 'Column LOWER_LIMIT does not exist'
GO

Comments

  • I am trying to do this:

    ALTER TABLE CompanyTransactions DROP COLUMN Created
    

    But I get this:

    Msg 5074, Level 16, State 1, Line 2
    The object ‘DF__CompanyTr__Creat__0CDAE408’ is dependent on column ‘Created’.
    Msg 4922, Level 16, State 9, Line 2
    ALTER TABLE DROP COLUMN Created failed because one or more objects access this column.

    This is a code first table. Somehow the migrations have become all messed up and I am trying to manually roll back some changed.

    I have no idea what this is:

    DF__CompanyTr__Creat__0CDAE408
    

  • It’s frustrating that Entity Framework doesn’t take care of this for us.

  • @chakeda I agree

  • To add to @malloc4k’s answer…you could expand the «Constraints» folder in SQL Server 2016 and it will show the «default» constraint names.

  • @user2513019 don’t forget to upvote it it helped you :)

  • I have similar situation. Problem is that my application is deployed to a lot of machines and all auto generated constraints have different names. How to deal with this sort of situation? Adding a long script that is generating sql from information_schema to the migration does not feel as a clean and good option.

  • @MantasDaškevičius The best option there is to name the constraint instead of using auto generated names.

Recents

Related

I’m migrating from a mysql database to SQLServer 2008 R2. For that I exported the mysql database using phpmyadmin, then use the generated SQL script. I make necessary changes to adjust column types and so far I managed to run every sql-statement (create
/ insert / update)

The last little task I need to accomplish consists of the following steps:

— create a new table , then insert … select data from another table

— alter the source-table to remove the columns that are now in the new created table

For that I have the simple SQL-Command:

ALTER

TABLE tickets
DROP
COLUMN flag;
commit;

But I’m getting an error :

Msg 5074, Level 16, State 1, Line 1
The object ‘DF__tickets__flag__7CA47C3F’ is dependent on column ‘flag’.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE DROP COLUMN flag failed because one or more objects access this column.

Also I didnt set any specific constraint .. except from a simple default-value during create table (flag integer default NULL,)

I can delete the columns (2 columns) with the SQL Server Management Studio (Express) easily but I need to do it with the script, since on the final machine there wont be management studio

I guess the exact Name of the DF-tickets-flag-constraint changes when I execute the script again

Is there some kind of SET-statement that enables me to automatically Drop the constraint together with the Columns ? Or any other way?

thanks for your support

Возможно, вам также будет интересно:

  • Ошибка amd превышение времени ожидания ответа драйвера
  • Ошибка alter table alter column
  • Ошибка amd драйвер не установлен
  • Ошибка alt аукс на рефрижераторе
  • Ошибка alt aux на carrier supra 850

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии