Ryan
Ryan

Reputation: 199

Foreign key references invalid table. Could not create constraint or index

I'm trying to create a table with 3 columns. The first column should be an identity column named DescriptionsID, the second column should be a foreign key column named ProductID, and the third column should be an xml column named Description. But, I'm receiving an error:

Foreign Key 'FK_ProductDescriptions_bacb18ce3aa67348e55d' references invalid table 'Product' and "Could not create constraint or index. See previous errors."

This is what I got:

CREATE TABLE ProductDescriptions (DescriptionsID int PRIMARY KEY NOT NULL,

ProductID varchar(25) NOT NULL,

FOREIGN KEY (ProductID) REFERENCES Product(ProductID),

Description text NULL) ;

References Product(ProductID) has the error/red underlining

Upvotes: 1

Views: 10592

Answers (1)

Jayasurya Satheesh
Jayasurya Satheesh

Reputation: 8043

When you create a Referential Constraint, You Need to make sure that the Table and the Column which you are referring already exists in the Database.

Also, the Datatype of Both Referring Column and the Referred Column Should Be the Same

Column 'Product.ProductId' is not the same data type as referencing column
'ProductDescriptions.ProductID' in the foreign key

So Create Product Table First, and set the Product Id as Primary Key

CREATE TABLE Product
(
    ProductId INT IDENTITY(1,1) PRIMARY KEY,
    ProductName VARCHAR(50)
)

CREATE TABLE ProductDescriptions 
(
    DescriptionsID int PRIMARY KEY NOT NULL,
    ProductID INT NOT NULL 
    ,FOREIGN KEY (ProductID) REFERENCES Product(ProductID),
    [Description] text NULL
) ;

Upvotes: 1

Related Questions