Меню

Ошибка alter table alter column так как один или несколько объектов обращаются к данному столбец

  • Remove From My Forums
  • Question

  • Hi

    when I’m upgrading table schema with alter statement

    I’m getting error like this

    ALTER TABLE ALTER COLUMN [access-id] failed because one or more objects access this column

    can Anybody tell the solutiuon plz.

    Thank u .

    vizai

Answers

  • If you have any View /UDF With SchemaBinding on this Base table , you are not allowed to change or Drop columns or Table Object..

    If you want to alter the table first you need to remove the SchemaBinding in all the views/UDF and change the column on Base table then recreate the Views/UDFs With SchemaBinding.

    If you have any Indexed Views when you remove the SchemaBinding all the Index on the Views will be removed, so you have to create them too..

  • Remove From My Forums
  • Question

  • Hi

    when I’m upgrading table schema with alter statement

    I’m getting error like this

    ALTER TABLE ALTER COLUMN [access-id] failed because one or more objects access this column

    can Anybody tell the solutiuon plz.

    Thank u .

    vizai

Answers

  • If you have any View /UDF With SchemaBinding on this Base table , you are not allowed to change or Drop columns or Table Object..

    If you want to alter the table first you need to remove the SchemaBinding in all the views/UDF and change the column on Base table then recreate the Views/UDFs With SchemaBinding.

    If you have any Indexed Views when you remove the SchemaBinding all the Index on the Views will be removed, so you have to create them too..

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.4k23 gold badges103 silver badges184 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,6443 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,8093 gold badges38 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,6764 gold badges20 silver badges42 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

5006 silver badges23 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

There are a variety of causes for the message shown in the title of this post. Manually creating statistics for a column is one such cause. This post shows how that works, and what you need to do to get around the error. Columns that have manually-created statistics attached cannot have their properties modified without first dropping the stats object – this is to ensure the stats object accurately reflects the content of the column. SQL Server returns an error message stating “ALTER TABLE ALTER COLUMN failed because one or more objects access this column.” I ran into this limitation recently when attempting to modify the datatype for a column from varchar to nvarchar. This database has auto create statistics disabled. As a result, manually creating statistics objects is critical to ensuring good query performance.

alter table alter column failed!

     Have a failed column or three!

The Error Message

When attempting to modify a column that has a manually created statistics object attached, you receive the following “ALTER TABLE ALTER COLUMN failed” error message:

Msg 5074, Level 16, State 1, Line 36
The statistics '<name>' is dependent on column '<col>'.
Msg 4922, Level 16, State 9, Line 36
ALTER TABLE ALTER COLUMN <col> failed because one or more objects access this column.

Interestingly, if SQL Server has auto-created a stats object on a column, and you subsequently modify that column, you receive no such error. SQL Server silently drops the statistics object, and modifies the column. The auto-created stats object is not automatically recreated until a query is executed that needs the stats object. This difference in how auto-created stats and manually created stats are treated by the engine can make for some confusion.

Ads by Google, Paying the Rent:

The Script

Consider the following minimally complete and verifiable example code that can be used to reproduce the problem:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

SET NOCOUNT ON;

USE master;

GO

—Create a new, blank database for our test

IF EXISTS (SELECT 1 FROM sys.databases d WHERE d.name = ‘test_stats_alter’)

BEGIN

    ALTER DATABASE test_stats_alter SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

    DROP DATABASE test_stats_alter;

END

CREATE DATABASE test_stats_alter;

ALTER DATABASE test_stats_alter SET AUTO_CREATE_STATISTICS OFF;

ALTER DATABASE test_stats_alter SET AUTO_UPDATE_STATISTICS OFF;

GO

USE test_stats_alter;

GO

CREATE TABLE dbo.stats_test

(

    id int NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED

    , d varchar(30) NOT NULL

);

CREATE TABLE dbo.dates

(

    d varchar(30) NOT NULL

)

GO

—Insert a bunch of rows to allow the query optimizer to perform actual work.

INSERT INTO dbo.stats_test (d)

SELECT CONVERT(datetime, DATEADD(DAY, CONVERT(int, CRYPT_GEN_RANDOM(2)), ‘1900-01-01T00:00:00’))

FROM sys.syscolumns sc1

    CROSS JOIN sys.syscolumns sc2

INSERT INTO dbo.dates (d)

SELECT CONVERT(datetime, DATEADD(DAY, CONVERT(int, CRYPT_GEN_RANDOM(2)), ‘1900-01-01T00:00:00’))

FROM sys.syscolumns sc1

GO

—Manually create a stats object

CREATE STATISTICS stats_test_st1

ON dbo.stats_test(d)

WITH FULLSCAN, NORECOMPUTE;

GO

—Attempt to alter the column with the manual stats object defined.

—This will fail with Msg 5074, Level 16, State 1, Line xx

ALTER TABLE dbo.stats_test

ALTER COLUMN d nvarchar(30) NOT NULL;

GO

SQL Server returns this error:

Msg 5074, Level 16, State 1, Line 47
The statistics 'stats_test_st1' is dependent on column 'd'.
Msg 4922, Level 16, State 9, Line 47
ALTER TABLE ALTER COLUMN d failed because one or more objects access this column.

Let’s continue on:

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

—drop the stats object

DROP STATISTICS dbo.stats_test.stats_test_st1;

GO

—Allow SQL Server to automatically create statistics

ALTER DATABASE test_stats_alter SET AUTO_CREATE_STATISTICS ON;

ALTER DATABASE test_stats_alter SET AUTO_UPDATE_STATISTICS ON;

GO

—Coerce SQL Server into automatically creating a stats object.

—This is a complex enough query that SQL Server recognizes a

—stats object would be helpful for good performance.

SELECT st.id

    , st.d

INTO dbo.stats_test_output

FROM dbo.stats_test st

    LEFT JOIN dbo.dates d ON st.d = d.d

WHERE st.d > ‘2017-06-01T00:00:00’;

GO

—See if SQL Server in fact created an auto-stats object on

—the column.

SELECT *

FROM sys.stats st

    INNER JOIN sys.objects o ON st.object_id = o.object_id

WHERE o.name = ‘stats_test’;

GO

╔════════════╦════════════════════════════════╦══════════════╗
║    name    ║              name              ║ auto_created ║
╠════════════╬════════════════════════════════╬══════════════╣
║ stats_test ║ PK__stats_te__3213E83FF58F8430 ║            0 ║
║ stats_test ║ _WA_Sys_00000002_21B6055D      ║            1 ║
╚════════════╩════════════════════════════════╩══════════════╝

—attempt to alter the table, which succeeds.

ALTER TABLE dbo.stats_test

ALTER COLUMN d nvarchar(30) NOT NULL;

GO

—check to see if the auto-created stats object still exists

SELECT *

FROM sys.stats st

    INNER JOIN sys.objects o ON st.object_id = o.object_id

WHERE o.name = ‘stats_test’;

The auto-created stats object has been silently dropped:

╔════════════╦════════════════════════════════╦══════════════╗
║    name    ║              name              ║ auto_created ║
╠════════════╬════════════════════════════════╬══════════════╣
║ stats_test ║ PK__stats_te__3213E83FF58F8430 ║            0 ║
╚════════════╩════════════════════════════════╩══════════════╝

In Summary

Manually adding statistics objects can be a blessing for performance, however you need to recognize the limitations this creates for future object modifications.

If you have auto_create_statistics turned off, you probably want to update your stats objects on a regular basis to ensure good performance. See my statistics update job for details about how to do that.

Read the other articles in our series on SQL Server Internals.

If you found this post useful, please
consider donating a small amount
to help keep the lights on and site running.

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

ALTER TABLE CompanyTransactions DROP COLUMN Created

но я понимаю это:

Msg 5074, Уровень 16, Состояние 1, Строка 2
Объект ‘ДФ__CompanyTr__Д__0CDAE408 зависит от созданных колонка’.
Msg 4922, Уровень 16, Состояние 9, Строка 2
Не удалось создать столбец ALTER TABLE DROP, так как один или несколько объектов обращаются к этому столбцу.

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

Я нет идея, что это такое:

DF__CompanyTr__Creat__0CDAE408

2 ответов


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

например

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

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

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int DEFAULT NULL;

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

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

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

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


  • Remove From My Forums
  • Question

  • Hi

    when I’m upgrading table schema with alter statement

    I’m getting error like this

    ALTER TABLE ALTER COLUMN [access-id] failed because one or more objects access this column

    can Anybody tell the solutiuon plz.

    Thank u .

    vizai

Answers

  • If you have any View /UDF With SchemaBinding on this Base table , you are not allowed to change or Drop columns or Table Object..

    If you want to alter the table first you need to remove the SchemaBinding in all the views/UDF and change the column on Base table then recreate the Views/UDFs With SchemaBinding.

    If you have any Indexed Views when you remove the SchemaBinding all the Index on the Views will be removed, so you have to create them too..

  • Remove From My Forums
  • Question

  • Hello Gurus,

                  I am trying to alter column data type length but its throwing me an error

    ALTER TABLE AR

    ALTER COLUMN ph
    VARCHAR(25)

    ERROR: The object ‘df_ar_PH’ is dependent on column ‘ph’.

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

Answers

  • you will need to drop and recreate the index.

    once you drop the constraints and index , you can alter the column .

    Then re create constraints and index.  

    • Edited by

      Wednesday, November 14, 2012 4:38 PM

    • Proposed as answer by
      Kalman Toth
      Tuesday, November 20, 2012 3:32 PM
    • Marked as answer by
      Iric Wen
      Thursday, November 22, 2012 9:04 AM

  • this might help :

    http://stackoverflow.com/questions/5727155/drop-a-column-from-table-problem-sql-server-2008

    • Proposed as answer by
      Kalman Toth
      Tuesday, November 20, 2012 3:32 PM
    • Marked as answer by
      Iric Wen
      Thursday, November 22, 2012 9:04 AM

  • Remove From My Forums
  • Question

  • Hello Gurus,

                  I am trying to alter column data type length but its throwing me an error

    ALTER TABLE AR

    ALTER COLUMN ph
    VARCHAR(25)

    ERROR: The object ‘df_ar_PH’ is dependent on column ‘ph’.

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

Answers

  • you will need to drop and recreate the index.

    once you drop the constraints and index , you can alter the column .

    Then re create constraints and index.  

    • Edited by

      Wednesday, November 14, 2012 4:38 PM

    • Proposed as answer by
      Kalman Toth
      Tuesday, November 20, 2012 3:32 PM
    • Marked as answer by
      Iric Wen
      Thursday, November 22, 2012 9:04 AM

  • this might help :

    http://stackoverflow.com/questions/5727155/drop-a-column-from-table-problem-sql-server-2008

    • Proposed as answer by
      Kalman Toth
      Tuesday, November 20, 2012 3:32 PM
    • Marked as answer by
      Iric Wen
      Thursday, November 22, 2012 9:04 AM

  • Remove From My Forums
  • Question

  • Hello Gurus,

                  I am trying to alter column data type length but its throwing me an error

    ALTER TABLE AR

    ALTER COLUMN ph
    VARCHAR(25)

    ERROR: The object ‘df_ar_PH’ is dependent on column ‘ph’.

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

Answers

  • you will need to drop and recreate the index.

    once you drop the constraints and index , you can alter the column .

    Then re create constraints and index.  

    • Edited by

      Wednesday, November 14, 2012 4:38 PM

    • Proposed as answer by
      Kalman Toth
      Tuesday, November 20, 2012 3:32 PM
    • Marked as answer by
      Iric Wen
      Thursday, November 22, 2012 9:04 AM

  • this might help :

    http://stackoverflow.com/questions/5727155/drop-a-column-from-table-problem-sql-server-2008

    • Proposed as answer by
      Kalman Toth
      Tuesday, November 20, 2012 3:32 PM
    • Marked as answer by
      Iric Wen
      Thursday, November 22, 2012 9:04 AM

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

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

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка antipollution fault пежо 207
  • Ошибка allmondbeard sea of thieves