简体   繁体   English

无法在现有表的主键上创建约束或索引或外键

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

I created a table Demo .我创建了一个表Demo I want its key Customer_ID_f to reference to primary key CustomerID of some other table named Customers .我希望它的键Customer_ID_f引用其他一些名为Customers CustomerID

DEMO Table(with foreign key) DEMO表(带外键)

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. Customers表的字符CustomerID信息。

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.如您所见,在Customers表中,主键的 nchar 长度为 5 (max_length),我在我的演示表中使用了相同的。 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'. “Customers.CustomerID”列与外键“FK__Demo__Customer_I__690797E6”中引用列“Demo.Customer_ID_f”的数据类型不同。

Msg 1750, Level 16, State 1, Line 156 Could not create constraint or index.消息 1750,级别 16,State 1,第 156 行无法创建约束或索引。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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