简体   繁体   中英

Could not create constraint or index or foreign key on primary key of existing table

I created a table Demo . I want its key Customer_ID_f to reference to primary key CustomerID of some other table named Customers .

DEMO Table(with foreign key)

CREATE TABLE Demo (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
Age int Not Null,
City varchar(200) DEFAULT 'Sydney',
OrderDate DATE DEFAULT getdate(),
CHECK (AGe>=18),
Customer_ID_f char(5) not null
PRIMARY KEY (ID),
FOREIGN KEY (Customer_ID_f) REFERENCES Customers(CustomerID))

Customers table with primary key

Information about the character CustomerID of Customers table.

Select *
From INFORMATION_SCHEMA.COLUMNS
Where TABLE_NAME = 'Customers';
    TABLE_SCHEMA    TABLE_NAME  COLUMN_NAME ORDINAL_POSITION    COLUMN_DEFAULT  IS_NULLABLE   DATA_TYPE CHARACTER_MAXIMUM_LENGTH    CHARACTER_OCTET_LENGTH      
    dbo             Customers  CustomerID            1         NULL             NO              nchar                     5                 10    

As you can see that in Customers table, the primary key has nchar of length 5 (max_length), i use the same with my demo table. Still I am getting error.

Error :

Column 'Customers.CustomerID' is not the same data type as referencing column 'Demo.Customer_ID_f' in foreign key 'FK__Demo__Customer_I__690797E6'.

Msg 1750, Level 16, State 1, Line 156 Could not create constraint or index. See previous errors.

Try this one:

CREATE TABLE Demo (
ID int NOT NULL  PRIMARY KEY identity(1,1),
LastName varchar(255) NOT NULL,
Age int Not Null,
City varchar(200) DEFAULT 'Sydney',
OrderDate DATE DEFAULT getdate(),
CHECK (AGe>=18),
Customer_ID_f nchar(5)
)

ALTER TABLE Demo 
ADD CONSTRAINT FK_Demo_Customer_ID 
FOREIGN KEY (Customer_ID_f) REFERENCES Customers(CustomerID)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM