Showing posts with label Referencess. Show all posts
Showing posts with label Referencess. Show all posts

Number of referencing columns in foreign key differs from number of referenced columns, table 'TableName'.

When creating/adding referential integrity constraints on a Table, The following error occurred in various scenarios as given below..

Number of referencing columns in foreign key differs from number of referenced columns, table 'TableName'.

Meaning:
Column name not specified for the foreign key constraints.

When creating table:
IF OBJECT_ID('Tb_Table2','U') IS NULL
CREATE TABLE Tb_Table2
(
Id INT,
Column2 VARCHAR(10),
CONSTRAINT FK_ID FOREIGN KEY REFERENCES Tb_Table1(Id)
)
GO


or

Adding foreign key constraint on existing table:
ALTER TABLE Tb_Table2 ADD CONSTRAINT FK_ID FOREIGN KEY REFERENCES Tb_Table1(Id)
GO


Column name not specified for Foreign key constraints in both scripts

The script should be as follows...

IF OBJECT_ID('Tb_Table2','U') IS NULL
CREATE TABLE Tb_Table2
(
Id INT,
Column2 VARCHAR(10),
CONSTRAINT FK_ID FOREIGN KEY(Id) REFERENCES Tb_Table1(Id)
)
GO


or

ALTER TABLE Tb_Table2 ADD CONSTRAINT FK_ID FOREIGN KEY(Id) REFERENCES Tb_Table1(Id)
GO


Here, Id is the Parent table Key column.