How to reference to primary key? - sql

create database [PostaShpejte]
use PostaShpejte
create table Posta
(
ID_Posta int not null Primary Key,
Emri varchar(50)not null,
Qyteti varchar(15) not null,
)
create table Dergesa
(
ID_Dergesa int IDENTITY(1,1) not null Primary Key,
Emri_Dergeses varchar(30) not null,
Pershkrimi varchar(100),
Qmimi int not null,
Statusi varchar(30) not null,
CONSTRAINT CHK_Statusi CHECK (Statusi='E regjistruar' or Statusi='E nisur' or Statusi='Ne depo' or Statusi='E refuzuar' or Statusi='E derguar'),
)
create table Menaxhon
(
ID_Dergesa int not null references Dergesa (ID_Dergesa),
ID_Posta int not null references Posta(ID_Posta),
Primary Key(ID_Dergesa,ID_Posta),
)
--drop table TelBleresi
create table TelBleresi
(
ID_Tel_Bleresi int not null,
--ID_Bleresi int not null,
NumriTel int not null Unique,
Primary Key(ID_Tel_Bleresi),
)
--drop table Bleresi
create table Bleresi
(
ID_Bleresi int not null,
ID_Tel_Bleresi int not null,
Emri varchar(20) not null,
Mbiemri varchar(20) not null,
Shteti varchar(20) not null,
Qyteti varchar(20) not null,
Rruga varchar(50) not null,
ZIPKodi int not null,
FOREIGN KEY(ID_Tel_Bleresi) references TelBleresi(ID_Tel_Bleresi),
Primary Key (ID_Bleresi , ID_Tel_Bleresi),
)
create table Dergohet
(
ID_Dergesa int not null,
ID_Bleresi int not null,
Data_e_regj date not null,
Data_e_mbrritjes date not null,
----------------PROBLEM HERE---------------------------
FOREIGN KEY (ID_Dergesa) references Dergesa(ID_Dergesa),
FOREIGN KEY (ID_Bleresi) references **Bleresi**(ID_Bleresi),
*Error: There are no primary or candidate key to table Bleresi ....*
---------------------------------------------------------
PRIMARY KEY (ID_Dergesa,ID_Bleresi),
)

Bleresi has a compound primary key (ID_Bleresi, ID_Tel_Bleresi), so you need to reference all columns. That means adding ID_Tel_Bleresi to Dergohet.
create table Dergohet(
ID_Dergesa int not null,
ID_Bleresi int not null,
ID_Tel_Bleresi int not null, -- add this column
Data_e_regj date not null,
Data_e_mbrritjes date not null,
FOREIGN KEY (ID_Dergesa) references Dergesa(ID_Dergesa),
-- Reference the full compound key
FOREIGN KEY (ID_Bleresi, ID_Tel_Bleresi) references Bleresi(ID_Bleresi, ID_Tel_Bleresi),
PRIMARY KEY (ID_Dergesa,ID_Bleresi),
)
While they have some uses, compound primary keys are annoying as they create a proliferation of foreign key columns and complicate indexing. Some of yours seem unnecessary: Bleresi already has a ID_Bleresi, is that not unique?
In general, I'd recommend using simple big integer (2 billion creeps up on you surprisingly fast) auto incrementing primary keys. If you need to guarantee other uniquenesses, make a unique index.

The error say that ID_Bleresi is not the primary key on Bleresi table and for that can't be a foreign key. The primary key is:
Primary Key (ID_Bleresi , ID_Tel_Bleresi)
If ID_Bleresi is not a unique column, I recommend that in the table, you create a new unique column that is the primary key. In case it is, it would be best to set ID_Bleresi as the unique primary key

Related

Error during foreign key creation: Invalid references

I have 2 tables and I want to create a foreign key constraint in the second table. This is what I tried:
Table 1:
CREATE TABLE REMINDER_RULE_M
(
REMINDER_RULE_M_D int IDENTITY(1,1) NOT NULL,
COMMUNICATION_MODE nvarchar(255) NOT NULL,
REMINDER_TO nvarchar(255) NOT NULL,
REMINDER_VALUE varchar(255) NOT NULL,
REMINDER_CONDITION varchar(255) NOT NULL,
REMINDER_TO_CUSTOM varchar(255)
)
Table 2:
CREATE TABLE REMINDER_AUDIT
(
REMINDER_AUDIT_D int IDENTITY(1,1) NOT NULL,
ACTION varchar(255) NOT NULL,
CONSTRAINT FK_b892318b20e5bbe162722ea5946
FOREIGN KEY (REMINDER_RULE_M_D)
REFERENCES REMINDER_RULE_M(REMINDER_RULE_M_D),
OLD_VALUE nvarchar(1024) NOT NULL,
NEW_VALUE nvarchar(1024) NOT NULL,
)
I get an error running the second SQL query:
Reason:
SQL Error [1769] [S0001]: Foreign key 'FK_b892318b20e5bbe162722ea5946' references invalid column 'REMINDER_RULE_M_D' in referencing table 'REMINDER_AUDIT'.
As the error clearly tells you - you don't have a column in your second table.
You must have a column in order to create a FK constraint - the FK constraint does NOT create a column in your table - it just establishes a constraint between existing tables and columns.
So try this for your second table:
CREATE TABLE REMINDER_AUDIT
(
REMINDER_AUDIT_D int IDENTITY(1,1) NOT NULL,
ACTION varchar(255) NOT NULL,
-- define the column!
REMINDER_RULE_M_D int NOT NULL,
-- I'd strongly recommend trying to come up with a more
-- intuitive and useful naming convention for your FK constraints!
CONSTRAINT FK_b892318b20e5bbe162722ea5946
FOREIGN KEY (REMINDER_RULE_M_D)
REFERENCES REMINDER_RULE_M(REMINDER_RULE_M_D),
OLD_VALUE nvarchar(1024) NOT NULL,
NEW_VALUE nvarchar(1024) NOT NULL,
)
I just guessed that REMINDER_RULE_M_D is NOT NULL - you might need to adapt this (if it's an optional key).
You do not need to write Foreign Key
CREATE TABLE REMINDER_AUDIT (
REMINDER_AUDIT_D int IDENTITY(1,1) NOT NULL,
ACTION varchar(255) NOT NULL,
CONSTRAINT FK_b892318b20e5bbe162722ea5946 REFERENCES REMINDER_RULE_M(REMINDER_RULE_M_D),
OLD_VALUE nvarchar(1024) NOT NULL,
NEW_VALUE nvarchar(1024) NOT NULL,
)

Error in create table T-SQL "Incorrect syntax near ','."

When create table have error "Incorrect syntax near ','."
I cant see this error in code. Please point out this error.
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null,
quantity INT NOT null,
inventory_numbers INT NOT NULL PRIMARY KEY)
CREATE TABLE systematic_catalog(
id INT NOT NULL IDENTITY PRIMARY KEY,
udc_id INT FOREIGN KEY REFERENCES books(udc),
knowledge_area VARCHAR)
CREATE TABLE issued_books(
date_issued DATETIME,
inventory_numbers_id INT FOREIGN KEY REFERENCES books(inventory_numbers))
CREATE TABLE readers(
id INT NOT NULL IDENTITY PRIMARY KEY,
last_name VARCHAR CONSTRAINT,
first_name VARCHAR CONSTRAINT,
middle_name VARCHAR,
phone_number INT(11),
address VARCHAR,
ticket_number INT CONSTRAINT,
date_registration DATETIME,
date_reregistratiom DATETIME,
issued_books_id FOREIGN KEY REFERENCES issued_books(inventory_numbers_id))
You cannot add multiple primary keys to the table, either composite ey (combination of two fields) or Unique constraint can be added instead.
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null,
quantity INT NOT null,
inventory_numbers INT NOT NULL PRIMARY KEY)
this is an error, you cannot ass multiple primary keys. Instead you can add Unique constraint
Correction would be,
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null Unique, --this is used to create the second table
quantity INT NOT null,
inventory_numbers INT NOT NULL Unique )
CREATE TABLE systematic_catalog(
id INT NOT NULL IDENTITY PRIMARY KEY,
udc_id INT FOREIGN KEY REFERENCES books(udc), --Referenced column needs to be unique
knowledge_area VARCHAR)
CREATE TABLE issued_books(
date_issued DATETIME,
inventory_numbers_id INT FOREIGN KEY REFERENCES books(inventory_numbers))
CREATE TABLE readers(
id INT NOT NULL IDENTITY PRIMARY KEY,
last_name VARCHAR (255),
first_name VARCHAR (255),
middle_name VARCHAR(255),
phone_number INT,
[address] VARCHAR(255),
ticket_number INT ,
date_registration DATETIME,
date_reregistratiom DATETIME)
You cannot use a foreign key of another table as a foreign key for some other table. You need to read more on table, Primary key constraints and foreign key referencing.
This cannot be done. you are trying to refer to the foreign key of issued_books table as a foreign key in readers table, which is wrong.
issued_books_id INT FOREIGN KEY REFERENCES issued_books(inventory_numbers_id))
I hope this explanation will give you a better understanding of errors. There were synatx errors as well as wrong use of the SQL table creation steps. I have added the corrected code for you. Feel free to contact any time.

Creating SQL database. with multiple primary and foreign keys

I'm currently working through an assignment that is asking me to create a SQL database using SQL Server Express. This is what it's asking for:
CREATE DATABASE USING SQL
And this is the code I have tried running;
CREATE DATABASE db_Library
Go
USE db_Library
CREATE TABLE tbl_library_branch
(
library_branch_branch_id INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_branch_branch_name VARCHAR(50) NOT NULL,
library_branch_address VARCHAR(50) NOT NULL
);
CREATE TABLE tbl_publisher
(
library_publisher_publisher_name VARCHAR(50) PRIMARY KEY NOT NULL,
library_publisher_address VARCHAR(50) NOT NULL,
library_publisher_phone INT NOT NULL
);
CREATE TABLE tbl_books
(
library_books_book_id INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_books_title VARCHAR(50) NOT NULL,
library_books_publisher_name VARCHAR(50) NOT NULL CONSTRAINT fk_library_books_publisher_name FOREIGN KEY REFERENCES tbl_publisher(library_publisher_publisher_name) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE tbl_book_authors
(
library_book_authors_book_id INT NOT NULL CONSTRAINT fk_library_book_authors_book_id FOREIGN KEY REFERENCES tbl_books(library_books_book_id) ON UPDATE CASCADE ON DELETE CASCADE,
library_book_authors_author_name VARCHAR(50) NOT NULL
);
CREATE TABLE tbl_book_copies
(
library_book_copies_book_id INT NOT NULL CONSTRAINT fk_library_book_copies_book_id FOREIGN KEY REFERENCES tbl_books(library_books_title),
library_book_copies_branch_id INT NOT NULL,
library_book_copies_number_of_copies INT NOT NULL
);
CREATE TABLE tbl_book_loans
(
library_book_loans_book_id INT NOT NULL,
library_book_loans_branch_id INT NOT NULL,
library_book_loans_card_no INT NOT NULL,
library_book_loans_date_out INT NOT NULL,
library_book_loans_date_due INT NOT NULL
);
CREATE TABLE tbl_borrower
(
library_borrower_card_no INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_borrower_name VARCHAR(50) NOT NULL,
library_borrower_address VARCHAR(50) NOT NULL,
library_borrower_phone VARCHAR(50) NOT NULL
);
Using the library "Books" as an example it looks like I need to have BoodID as a primary key and Title as a primary key, but you can't have more than one primary key per table..
Then I have to take BookID from the Book_Copies table and the Book_Loans table connect to the primary key of Title in Books?
I'm beyond stuck at this point and would appreciate any resources you think could help.
There is no need to be so verbose. I think you want something more like this (for two tables):
CREATE TABLE tbl_publisher (
publisher_id int IDENTITY(1, 1) PRIMARY KEY,
publisher_name VARCHAR(50) NOT NULL UNIQUE,
address VARCHAR(50) NOT NULL,
phone INT NOT NULL
);
CREATE TABLE books (
book_id INT IDENTITY (1,1) PRIMARY KEY,
title VARCHAR(50) NOT NULL UNIQUE,
publisher_id INT NOT NULL CONSTRAINT fk_books_publisher__id FOREIGN KEY REFERENCES tbl_publisher(publisher_id) ON UPDATE CASCADE ON DELETE CASCADE
);
Notes:
Stick with synthetic primary keys for all the tables. That is, identity columns.
Other columns can be declared to be unique. That is fine.
I type quite fast. And yet I would quickly wary of typing library_book_ over and over. Such repetition just makes it harder to write and read queries.

Why do my CREATE TABLES work alone but not together? [duplicate]

This question already has answers here:
How do I execute multiple SQL Statements in Access' Query Editor?
(6 answers)
Closed 4 years ago.
I am trying to run a script with multiple CREATE TABLE statements in MS Access.
When I try to run the script all together I get a CREATE TABLE syntax error on the 2nd CREATE TABLE, but when I run each CREATE TABLE on its own through a SQL validator they pass successfully.
What am I doing wrong by lumping all the CREATE TABLEs into one script?
CREATE TABLE MODEL (
ModelNum INT NOT NULL,
Capacity INT NOT NULL,
MaxRange INT NOT NULL,
CONSTRAINT ModelPK PRIMARY KEY(ModelNum)
);
CREATE TABLE AIRPLANE (
RegNum INT NOT NULL,
ModelNum INT NOT NULL,
CONSTRAINT AirplanePK PRIMARY KEY(RegNum),
CONSTRAINT AirplaneFK FOREIGN KEY(ModelNum) REFERENCES MODEL(ModelNum)
);
CREATE TABLE EMPLOYEE (
SSN INT NOT NULL,
EmpName VARCHAR(100) NOT NULL,
Phone INT NULL,
UnionMemberNum INT NULL,
CONSTRAINT EmployeePK PRIMARY KEY(SSN)
);
CREATE TABLE TECHNICIAN (
SSN INT NOT NULL,
Salary INT NOT NULL,
CONSTRAINT TechnicianPK PRIMARY KEY(SSN),
CONSTRAINT TechnicianFK FOREIGN KEY(SSN) REFERENCES EMPLOYEE(SSN)
);
CREATE TABLE TRAFFICCONTROLLER (
SSN INT NOT NULL,
DateOfTraining DATE NULL,
CONSTRAINT TrafficControllerPK1 PRIMARY KEY(SSN),
CONSTRAINT TrafficControllerFK1 FOREIGN KEY(SSN) REFERENCES EMPLOYEE(SSN)
);
CREATE TABLE EXPERT(
SSN INT NOT NULL,
ModelNum INT NOT NULL,
CONSTRAINT ExpertPK1 PRIMARY KEY(SSN),
CONSTRAINT ExpertFK1 FOREIGN KEY(ModelNum) REFERENCES AIRPLANE(ModelNum)
);
CREATE TABLE TEST(
Test_Num INT NOT NULL,
TestName VARCHAR(100) NOT NULL,
MaxScore INT NOT NULL,
CONSTRAINT TestPK PRIMARY KEY(Test_Num)
);
CREATE TABLE TESTEVENTS(
RegNum INT NOT NULL,
Test_Num INT NOT NULL,
SSN INT NOT NULL,
TestDate DATE NOT NULL,
Score INT NULL,
CONSTRAINT TestEventsPK1 PRIMARY KEY(RegNum),
CONSTRAINT TestEventsFK1 FOREIGN KEY(RegNum) REFERENCES AIRPLANE(RegNum),
CONSTRAINT TestEventsPK2 PRIMARY KEY(Test_Num),
CONSTRAINT TestEventsFK2 FOREIGN KEY(Test_Num) REFERENCES TEST(Test_Num),
CONSTRAINT TestEventsPK3 PRIMARY KEY(SSN),
CONSTRAINT TestEventsFK3 FOREIGN KEY(SSN) REFERENCES TECHNICIAN(SSN),
CONSTRAINT TestEventsPK4 PRIMARY KEY(TestDate)
);
MS Access supports only one statement at a time.

Foreign key constraint error during SQL Server table creation

I am trying to create a table on SQL Server which has foreign key constraints.I checked all my parent tables and their primary keys match with my new foreign key constraints. Can someone help me out in resolving this issue. My DDL and error message are as below.
DDL
CREATE TABLE I_IPV_LOB_PROG_PROV_MO_METRIC_TRNS(
AARP_ORG_ID int NOT NULL,
LOB_ID int NOT NULL,
PGM_CAT_ID int NOT NULL,
PGM_ID int NOT NULL,
PROV_ID int NOT NULL,
CAT_OF_MEAS_ID int NOT NULL,
SUBCAT_OF_MEAS_ID int NOT NULL,
MEAS_ID int NOT NULL,
TYPE_OF_METRIC_ID int NOT NULL,
METRIC_VAL_ROLE_ID int NOT NULL,
MO_ID int NOT NULL,
OPER_TXT varchar(5) NULL,
METRIC_VAL decimal(19, 2) NOT NULL,
LST_UPD_DT datetime NOT NULL,
LOAD_DT datetime NULL,
LST_UPD_USERID char(20) NOT NULL,
CONSTRAINT PK79 PRIMARY KEY NONCLUSTERED (TYPE_OF_METRIC_ID, METRIC_VAL_ROLE_ID, AARP_ORG_ID, LOB_ID, PGM_CAT_ID, PGM_ID, PROV_ID, MEAS_ID, MO_ID, CAT_OF_MEAS_ID, SUBCAT_OF_MEAS_ID),
CONSTRAINT RefI_IPV_TYPE_OF_METRIC_TRNS73 FOREIGN KEY (TYPE_OF_METRIC_ID)
REFERENCES I_IPV_TYPE_OF_METRIC_TRNS(TYPE_OF_METRIC_ID),
CONSTRAINT RefI_IPV_METRIC_VAL_ROLE_TRNS75 FOREIGN KEY (METRIC_VAL_ROLE_ID)
REFERENCES I_IPV_METRIC_VAL_ROLE_TRNS(METRIC_VAL_ROLE_ID),
CONSTRAINT RefI_IPV_LOB_PROG_PROV_MEAS_TRNS345 FOREIGN KEY (AARP_ORG_ID,LOB_ID,PGM_CAT_ID,PGM_ID,PROV_ID,MEAS_ID,CAT_OF_MEAS_ID,SUBCAT_OF_MEAS_ID)
REFERENCES I_IPV_LOB_PROG_PROV_MEAS_TRNS(AARP_ORG_ID,LOB_ID,PGM_CAT_ID,PGM_ID,PROV_ID,MEAS_ID,CAT_OF_MEAS_ID,SUB_CAT_OF_MEAS_ID)
)
go
Parent Table DDL
CREATE TABLE I_IPV_LOB_PROG_PROV_MEAS_TRNS(
AARP_ORG_ID int NOT NULL,
LOB_ID int NOT NULL,
PGM_CAT_ID int NOT NULL,
PGM_ID int NOT NULL,
PROV_ID int NOT NULL,
CAT_OF_MEAS_ID int NOT NULL,
SUBCAT_OF_MEAS_ID int NOT NULL,
MEAS_ID int NOT NULL,
LOAD_DT datetime NULL,
LST_UPD_USERID char(20) NOT NULL,
LST_UPD_DT datetime NOT NULL,
CONSTRAINT PK115 PRIMARY KEY NONCLUSTERED (MEAS_ID, PROV_ID, AARP_ORG_ID, LOB_ID, PGM_ID, PGM_CAT_ID, CAT_OF_MEAS_ID, SUBCAT_OF_MEAS_ID),
CONSTRAINT RefI_IPV_LOB_PROG_CAT_PROV_TRNS322 FOREIGN KEY (PROV_ID, AARP_ORG_ID, LOB_ID, PGM_ID, PGM_CAT_ID)
REFERENCES I_IPV_LOB_PROG_CAT_PROV_TRNS(PROV_ID, AARP_ORG_ID, LOB_ID, PGM_ID, PGM_CAT_ID),
CONSTRAINT RefI_IPV_MEAS_CAT_TRNS342 FOREIGN KEY (MEAS_ID, CAT_OF_MEAS_ID, SUBCAT_OF_MEAS_ID)
REFERENCES I_IPV_MEAS_CAT_TRNS(MEAS_ID, CAT_OF_MEAS_ID, SUBCAT_OF_MEAS_ID)
)
go
Error Msg
Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'I_IPV_LOB_PROG_PROV_MEAS_TRNS' that match the referencing column list in the foreign key 'RefI_IPV_LOB_PROG_PROV_MEAS_TRNS345'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
One of the fields in the target table must be its primary key (best) or be very quickly findable via some index using the at least one of nthe fields you've listed. If there are no keys in your list it will have to read the whole table to find the specific row and this is not a good thing to do, so it won't.
Create a unique index on the target table containing some/all of the fields you're constraining and it should be OK.