SQL Server : there are no primary or candidate keys in the referenced table - sql

I using SQL Server 2008, and when I try create a new table, in existing DB, this error appears:
There are no primary or candidate keys in the referenced table 'parceria_conta_corrente_ao' that match the referencing column list in the foreign key 'R_795'.
This table exists:
And I try create a new table with this code:
CREATE TABLE parceria_item_resgate_rateio_aux
(
id_parceria_item_resgate_rateio_aux int NOT NULL IDENTITY,
dt_conta_corrente DATETIME NOT NULL ,
id_periodo BIGINT NOT NULL ,
id_ao bigint NOT NULL ,
id_gr_cliente int NOT NULL ,
id_cliente BIGINT NOT NULL ,
data_importacao_cli_gr_cli DATETIME NOT NULL ,
hp2 varchar(50) NOT NULL ,
hp2_filho varchar(50) NOT NULL ,
valor_nc decimal(18,2) NULL ,
datetime_inclusion datetime NOT NULL ,
status int NULL ,
CONSTRAINT XPKparceria_item_resgate_ PRIMARY KEY CLUSTERED
(id_parceria_item_resgate_rateio_aux ASC,
dt_conta_corrente ASC,
id_periodo ASC,
id_ao ASC,
id_gr_cliente ASC,
id_cliente ASC,
data_importacao_cli_gr_cli ASC,
hp2 ASC),
CONSTRAINT R_795 FOREIGN KEY(dt_conta_corrente, id_periodo, id_ao, id_gr_cliente, id_cliente, data_importacao_cli_gr_cli, hp2)
REFERENCES parceria_conta_corrente_ao(dt_conta_corrente, id_periodo, id_ao, id_gr_cliente, id_cliente, data_importacao_cli_gr_cli, hp2)
ON DELETE CASCADE
ON UPDATE CASCADE
)
go
Where is the problem?

You need to create a unique index on the referenced table:
CREATE UNIQUE INDEX UX_parceria_conta_corrente_ao
ON parceria_conta_corrente_ao
(
dt_conta_corrente,
id_periodo,
id_ao,
id_gr_cliente,
id_cliente,
data_importacao_cli_gr_cli,
hp2
)
EDIT:
I guess the columns are not in the same order, columns in primary key must be in the same order than the columns in the foreing key.
If you execute the following:
CREATE TABLE T
(
C1 int NOT NULL,
C2 int NOT NULL,
PRIMARY KEY (C1, C2)
)
CREATE TABLE T2
(
id INT NOT NULL,
C1 int NOT NULL,
C2 int NOT NULL,
CONSTRAINT FK1 FOREIGN KEY (C2, C1) REFERENCES T(C2, C1)
)
You get the following error:
Msg 1776, Level 16, State 0, Line 9 There are no primary or candidate
keys in the referenced table 'T' that match the referencing column
list in the foreign key 'FK1'. Msg 1750, Level 16, State 0, Line 9
Could not create constraint or index. See previous errors.

Related

SQL. How I can create 2 or more foreign keys in a table? [duplicate]

This question already has answers here:
There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key
(4 answers)
Closed yesterday.
I want to create a table, that stores available books based on a QUANTITY value. If quantity > 0 this book is available. But I have an error:
Msg 1776, Level 16, State 0, Line 48
There are no primary or candidate keys in the referenced table 'BOOK_INFO' that match the referencing column list in the foreign key 'FK_QUANTITY'.
Msg 1750, Level 16, State 1, Line 48
Could not create constraint or index. See previous errors.
Code (the problem is table 'AVAILABLE_BOOKS'):
CREATE TABLE BOOKS
(
ID INT IDENTITY PRIMARY KEY,
BOOK_NAME VARCHAR(30) NOT NULL,
BOOK_AUTHOR VARCHAR(30) NOT NULL
)
CREATE TABLE BOOK_INFO
(
BOOK_ID INT PRIMARY KEY FOREIGN KEY REFERENCES BOOKS(ID),
QUANTITY INT DEFAULT 1 NOT NULL,
PRICE DECIMAL(5,2) NOT NULL,
CONSTRAINT CHECK_PRICE CHECK (PRICE > 0),
CONSTRAINT CHECK_QUANTITY CHECK (QUANTITY > 0)
)
CREATE TABLE ABAILABLE_BOOKS
(
BOOK_ID INT PRIMARY KEY,
QUANTITY INT DEFAULT 1 NOT NULL,
CONSTRAINT FK_BOOK_ID FOREIGN KEY (BOOK_ID) REFERENCES BOOKS(ID),
CONSTRAINT FK_QUANTITY FOREIGN KEY (QUANTITY) REFERENCES BOOK_INFO(QUANTITY),
CONSTRAINT CHECK_QUANTITY CHECK (QUANTITY > 0)
)
I was trying to change field declaration (QUANTITY INT -> QUANTITY INT DEFAULT 1 NOT NULL) ,
and many other things that didn't help.
You need to create an UNIQUE index on BOOK_INFO(QUANTITY)
CREATE TABLE BOOKS (
ID INT IDENTITY PRIMARY KEY,
BOOK_NAME VARCHAR(30) NOT NULL,
BOOK_AUTHOR VARCHAR(30) NOT NULL
)
CREATE TABLE BOOK_INFO (
BOOK_ID INT PRIMARY KEY FOREIGN KEY REFERENCES BOOKS(ID),
QUANTITY INT DEFAULT 1 NOT NULL,
PRICE DECIMAL(5,2) NOT NULL,
CONSTRAINT CHECK_PRICE CHECK (PRICE > 0),
CONSTRAINT CHECK_QUANTITY CHECK (QUANTITY > 0)
)
CREATE UNIQUE INDEX IX_BOOK_INFO_QUANTITY ON BOOK_INFO(QUANTITY)
CREATE TABLE ABAILABLE_BOOKS
(
BOOK_ID INT PRIMARY KEY,
QUANTITY INT DEFAULT 1 NOT NULL,
CONSTRAINT FK_BOOK_ID FOREIGN KEY (BOOK_ID) REFERENCES BOOKS(ID),
CONSTRAINT FK_QUANTITY FOREIGN KEY (QUANTITY) REFERENCES BOOK_INFO(QUANTITY),
CONSTRAINT ABAILABLE_BOOKS_CHECK_QUANTITY CHECK (QUANTITY > 0)
)

ALTER TABLE statement conflicted with the FOREIGN KEY constraint

When creating the foreign key I came across this error. Below is my code.
create table tblPerson(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int
)
create table tblGender (
ID int not null primary key,
Gender varchar(50) not null
)
alter table tblPerson add constraint tblPerson_GenderId_FK
foreign key (GenderId) references tblGender(ID)
You want to identify any "do not align" rows....
I have made the below.
You won't be able to add the FK constraint, if any rows come back from the SELECT query.
I have also removed the hungarian notation for "tbl". I would advise against it.
create table dbo.Person(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int )
create table dbo.Gender (
ID int not null primary key,
Gender varchar(50) not null
)
/* any rows below? your FK creation will fail */
Select *, p.GenderId as 'HoustonWeHaveAProblemValue' from dbo.Person p Where Not Exists (Select 1 from dbo.Gender g where g.ID = p.GenderId)
alter table dbo.Person add constraint Person_GenderId_FK
foreign key (GenderId) references dbo.Gender(ID)
Hi please use the following code to achieve your goal :
1-First create tblGender:
create table tblGender (
ID int not null primary key,
Gender varchar(50) not null
)
2-Then create table tblPerson with the relationship between 2 tables since the beginning:
create table tblPerson(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int references tblGender(ID)
)
works fine.

Problem with Constraint or Index SQL when Creating a Table

I'm currently working on an assignment and have run into an issue.
I get an error:
Msg 8135, Level 16, State 0, Line 41
Table level constraint or index does not specify column list, table 'Sessions'.
I've run through it a million times, but I cannot find out where the issue arises. I believe I AM specifying the columns in both table-level statements, so I am at a loss.
Here is the code:
CREATE TABLE Class
(
-- Column specifications and constraints--
ClassID NCHAR(6) NOT NULL,
ClassDescription NVARCHAR(50) NOT NULL,
--Table constraints--
CONSTRAINT pk_Class_ClassID
PRIMARY KEY (ClassID) --ClassID is the primary key in the Class table, done as a table constraint
)
CREATE TABLE Riders
(
-- Column specifications and constraints--
RiderID INT NOT NULL IDENTITY(10, 1) --RiderID auto-fills in the value, starting at 10, incrementing by 1
CONSTRAINT pk_Riders_RiderID PRIMARY KEY, --RiderID is the primary key in the Riders table
[Name] NVARCHAR(50) NOT NULL
CONSTRAINT chk_Riders_Name CHECK (LEN([Name]) > 4), --Name must be longer than 4 letters
ClassID NCHAR(6) NULL,
--Table constraints--
CONSTRAINT fk_Riders_Class
FOREIGN KEY (ClassID) REFERENCES Class (ClassID)
)
CREATE TABLE [Sessions]
(
-- Column specifications and constraints--
RiderID INT NOT NULL,
BikeID NCHAR(6) NOT NULL,
SessionDate DATETIME NOT NULL
CONSTRAINT chk_Sessions_SessionDate CHECK (SessionDate > '1 Sep 2017'), --SessionDate must be AFTER September 1, 2017
Laps INT NULL,
-- Table constraints--
CONSTRAINT pk_Sessions_RiderID_BikeID_SessionDate
PRIMARY KEY (RiderID, BikeID, SessionDate), --RiderID, BikeID, SessionDate is the composite primary key for the Sessions table
INDEX CI_Sessions_RiderID_BikeID ON [Sessions] (RiderID, BikeID) --Index RiderID and BikeID
)
CREATE TABLE Bikes
(
-- Column specifications and constraints--
BikeID NCHAR(6) NOT NULL
CONSTRAINT chk_Bikes_BikeID CHECK (BikeID LIKE '[0-9][0-9][0-9][HYS]-[AP]') --BikeID in format ###X-A # = 0 - 9, X = H(Honda), Y(Yamaha), S(Suzuki), A = A(AM), P(PM)
CONSTRAINT pk_Bikes_BikeID PRIMARY KEY, --BikeID is the primary key in the Bikes table
StableDate DATE NOT NULL
CONSTRAINT def_Bikes_StableDate DEFAULT GETDATE()
)
ALTER TABLE [Sessions]
ADD CONSTRAINT chk_Sessions_Laps CHECK (Laps >= 10)
ALTER TABLE [Sessions]
ADD CONSTRAINT fk_Sessions_Riders
FOREIGN KEY (RiderID) REFERENCES Riders (RiderID)
ALTER TABLE [Sessions]
ADD CONSTRAINT fk_Sessions_Bikes
FOREIGN KEY (BikeID) REFERENCES Bikes (BikeID)
Any help is appreciated!!
Just remove ON [Sessions] from index definition and write as:
CREATE TABLE [Sessions]
(
--Field specifications and constraints--
RiderID int not null,
BikeID nchar(6) not null,
SessionDate datetime not null
constraint chk_Sessions_SessionDate check (SessionDate > '1 Sep 2017'), --SessionDate must be AFTER September 1, 2017
Laps int null,
--Table constraints--
constraint pk_Sessions_RiderID_BikeID_SessionDate primary key (RiderID, BikeID, SessionDate), --RiderID, BikeID, SessionDate is the composite primary key for the Sessions table
INDEX CI_Sessions_RiderID_BikeID (RiderID, BikeID) --Index RiderID and BikeID
)
You can check which indexes are created using following script:
SELECT OBJECT_NAME(object_id) AS table_name,
name AS index_name,
type, type_desc
FROM sys.indexes
WHERE object_id = OBJECT_ID(N'dbo.Sessions', N'U');
Demo here..
This error can occur if you use the keyword "Index" or "index" as a column name in your sql table. To fix this, use "indx" or something else.

SQL Server return one row foreign key by use inner join

I have two tables:
Table 1 - projects and the structure is
create table Projects
(
ProjectID int identity(1,1) primary key ,
ProjectName varchar(900) not null,
ProjectCity varchar(500) not null,
ProjectAddress varchar(900) not null,
ProjectStatus bit not null,
projectCategories int not null ,
constraint fk2
foreign key(projectCategories)
references Categories(CategoriesID )
)
Table 2 is
create table imgProject
(
ProjectID int identity(1,1) primary key ,
Imagecontent image not null,
FkProject int not null ,
constraint fk1
foreign key(FkProject)
references Projects(ProjectID)
on delete cascade
)
How can I return project with only one row from table img project
I mean I want return all the project with only one column from table imgProject.
and example
After execute the query
id project [1] , NameProject [test] , Imagecontent [data]
not return all the row match with id foreign key on table imgproject

SQL Server Foreign Key Constraint References Invalid Table

I have the following code:
CREATE TABLE _CLIENT
(
client_id int ,
client_name varchar(50),
type varchar(50),
constraint _CLIENT_pk PRIMARY KEY(client_id),
constraint _CLIENT_ch CHECK (client_id>0),
typee_id INT NOT NULL REFERENCES CLIENT_TYPE(typee_id)
)
CREATE TABLE CLIENT_TYPE
(
typee_id int NOT NULL,
name_type varchar(50),
constraint CLIENT_TYPE_pk PRIMARY KEY(typee_id)
)
The foreign key throws an error saying:
Foreign key 'FK__Number__Name__1CF15040' references invalid table 'Users.Name'
what's the wrong here?
I don't know what exact error message you are getting, but you have error in the current script and I think you mean this error:
Foreign key 'FK___CLIENT__typee_i__55BFB948' references invalid table
'CLIENT_TYPE'.
You should first create CLIENT_TYPE table, so the script should look like:
CREATE TABLE CLIENT_TYPE
(
typee_id INT NOT NULL ,
name_type VARCHAR(50) ,
CONSTRAINT CLIENT_TYPE_pk PRIMARY KEY ( typee_id )
)
CREATE TABLE _CLIENT
(
client_id INT ,
client_name VARCHAR(50) ,
type VARCHAR(50) ,
CONSTRAINT _CLIENT_pk PRIMARY KEY ( client_id ) ,
CONSTRAINT _CLIENT_ch CHECK ( client_id > 0 ) ,
typee_id INT NOT NULL
REFERENCES CLIENT_TYPE ( typee_id )
)
As a general rule, you should first create base tables and then tables which depend on those ones.