'invalid for creating a default constraint' error when trying to add a constraint to an existing table

StackOverflow https://stackoverflow.com/questions/18149388

문제

I want to add a default constraint using ALTER TABLE in SQL Server, but I received the below error message instead.

Column 'StartDate' in table 'Register' is invalid for creating a default constraint.

I know that I can declare a constraint when I create a table, but that isn't the situation I am in. I hope someone can help me ;)

Here is my alter statement:

ALTER TABLE [dbo].[Register]
  ADD CONSTRAINT [Register_StartDate] DEFAULT (GETDATE()) FOR StartDate 

And this is my create table script:

CREATE TABLE [dbo].[Register]
  (
     [ID]        [INT] IDENTITY(1, 1) NOT NULL,
     /* ....*/
     [StartDate] [DATETIME] NULL
  ) 

Edited: Fixed: I forgot that the [StartDate] field doesn't even exist in the table. My bad!

도움이 되었습니까?

해결책

As far as I'm aware there are two possible circumstances that might cause this error.

Attempting to add a default constraint to:

  1. A computed column.
  2. A column that doesn't exist at all!

For the table definition

CREATE TABLE dbo.Register
  (
     ID INT IDENTITY(1, 1) NOT NULL,
     Computed AS 'Foo'
  ) 

Both of the following statements fail with error 1752.

ALTER TABLE dbo.Register
  ADD CONSTRAINT C1 DEFAULT 'X' FOR Computed

ALTER TABLE [dbo].[Register]
  ADD CONSTRAINT [Register_StartDate] DEFAULT (GETDATE()) FOR StartDate 

There are various other conditions on which it is not permissible to add a default constraint to a column but these all have their own unique error numbers and messages.

+------------------------------------+--------------+
|               Reason               | Error number |
+------------------------------------+--------------+
| Column is IDENTITY                 |         1754 |
| Column is timestamp/rowversion     |         1755 |
| Sparse Column                      |         1791 |
| Default constraint already present |         1781 |
+------------------------------------+--------------+

다른 팁

Error 1752 suggests that column name referenced in the constraint definition does not exist. Cross check if column exists in the table or if we are referencing incorrect name in default constraint definition.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top