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

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.

Related

How to reference to primary key?

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

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.

SQL ALTER TABLE foreign key

I have a problem with adding foreign keys with alter table command. I don't know how to make it so it works.
I need to add ISIK_ID and STAADION_ID to ISIK_STAADIONIL table as foreign key.
Here is my code:
CREATE TABLE ISIK(
ISIK_ID INT NOT NULL,
EESNIMI VARCHAR(25) NOT NULL,
PEREKONNANIMI VARCHAR(25) NOT NULL,
ISIKUKOOD VARCHAR(20),
KODAKONDSUS VARCHAR(30),
SUGU CHAR(1) NOT NULL,
HARIDUSTASE CHAR(1) NOT NULL,
TELEFONI_NR VARCHAR(20),
SYNNIPAEV DATE,
CONSTRAINT ISIK_ID_PK PRIMARY KEY (ISIK_ID)
);
CREATE TABLE ISIK_STAADIONIL(
ISIK_STAADIONIL_ID INT NOT NULL,
CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_STAADIONIL_ID),
ALATES TIMESTAMP,
KUNI TIMESTAMP
);
CREATE TABLE STAADION(
STAADION_ID INT NOT NULL,
NIMETUS VARCHAR(20),
KIRJELDUS VARCHAR(100),
ASUKOHT VARCHAR(50),
SUURUS VARCHAR(20),
MAHUTAVUS INT,
EHITATUD VARCHAR(20),
EHITAJA VARCHAR(20),
CONSTRAINT STAADION_ID_PK PRIMARY KEY (STAADION_ID)
);
ALTER TABLE ISIK_STAADIONIL
ADD CONSTRAINT ISIK_ID_FK
FOREIGN KEY(ISIK_ID)
REFERENCES ISIK(ID);
You need to add the columns first (to the table) before you can create FK constraints using them.
CREATE TABLE ISIK_STAADIONIL(
ISIK_STAADIONIL_ID INT NOT NULL,
CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_STAADIONIL_ID),
ALATES TIMESTAMP,
KUNI TIMESTAMP,
ISIK_ID INT,
STAADION_ID INT
);
And then your ALTER statement should work fine.
UPDATE
Changing the table-design slightly would make more sense, as per following. The logic is that ISIK_ID and STAADION_ID would together be sufficient to determine uniqueness in the ISIK_STAADIONIL table, so a separate ID is redundant:
CREATE TABLE ISIK_STAADIONIL(
ISIK_ID INT NOT NULL,
STAADION_ID INT NOT NULL,
CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_ID, STAADION_ID),
ALATES TIMESTAMP,
KUNI TIMESTAMP
);

There are no primary or candidate keys in the referenced table 'PayRoll' that match the referencing column list in the foreign key 'fk_EmployeeNumber'

I'm having some problem with the table called HoursandEarnings and I kept getting an error saying,
"There are no primary or candidate keys in the referenced table
'PayRoll' that match the referencing column list in the foreign key
'fk_EmployeeNumber'"
create table Address
(
PostalCode nvarchar(6) not null,
Address nvarchar(50) not null,
City nvarchar(30) not null,
Province nvarchar(30) not null,
constraint pk_postalcode primary key(PostalCode)
)
create table Payperiod
(
StartDate DateTime not null,
EndDate DateTime not null,
constraint pk_StartDate primary key(StartDate)
)
create table PayRoll
(
EmployeeNumber nvarchar(30) not null,
StartDate DateTime not null
constraint fk_StartDate references Payperiod(StartDate),
PostalCode nvarchar(6) not null
constraint fk_PostalCode references Address(PostalCode),
Department nvarchar(50) not null,
TotalEarningsCurrent decimal(5,2) not null,
TotalEarningsYearToDate decimal(5,2) not null,
Netpay decimal(5,2) not null,
EmployeeName nvarchar(30) not null,
constraint pk_PayRoll primary key(EmployeeNumber,StartDate)
)
create table HoursandEarnings
(
EmployeeNumber nvarchar(30) not null
constraint fk_EmployeeNumber references PayRoll(EmployeeNumber),
StartDate DateTime not null
constraint fk_StartDate references Payperiod(StartDate),
HoursAndEarningsDescription nvarchar(50) not null,
HoursandEarningsCurrent decimal(5,2) not null,
HoursandEarningsYearToDate decimal(5,2) not null,
constraint pk_HoursandEarnings primary
key clustered(EmployeeNumber,StartDate,HoursAndEarningsDescription)
)
create table EmployerPaidBenefits
(
EmployeeNumber nvarchar(30) not null
constraint fk_EmployerPaidBenefits_EmployeeNumber references PayRoll(EmployeeNumber),
StartDate DateTime not null
constraint fk_EmployerPaidBenefits_StartDate references Payperiod(StartDate),
EmployerpaidBenefitsDescription nvarchar(50) not null,
EmployerPaidBenefitsCurrent decimal(5,2) not null,
EmployerPaidBenefitsYearToDate decimal(5,2) not null
constraint pk_EmployerPaidBenefits
primary key(EmployeeNumber,StartDate,EmployerpaidBenefitsDescription)
)
create table Taxesanddeductions
(
EmployeeNumber nvarchar(30) not null,
constraint fk_Taxesanddeductions_EmployeeNumber references PayRoll(EmployeeNumber),
StartDate DateTime not null
constraint fk_Taxesanddeductions_StartDate references Payperiod(StartDate),
TaxesandDeductionsDescription nvarchar(50) not null,
TaxesandDeductionsCurrent decimal(5,2) not null,
EmployerPaidBenefitsYeartoDate decimal(5,2) not null,
constraint pk_Taxesanddeductions
primary key(EmployeeNumber,StartDate,TaxesandDeductionsDescription)
)
Because you have a composite key (EmployeeNumber,StartDate) on table PayRoll, you will need to reference both keys in the foreign key in the other tables which reference it.
If EmployeeNumber is unique in table Payroll, then you can make just EmployeeNumber the primary key on Payroll, and then your foreign keys on the other 3 tables to Payroll will be valid as-is.(Not the case)
Not related, but I believe you may run into problems making PostalCode a primary key on Address - this will mean that only one address with the same PostalCode may be added to the table. I would suggest a surrogate key instead.
Edit
Example of both columns in the foreign key:
constraint fk_HE_EmployeeNumber
foreign key(EmployeeNumber, StartDate)
references PayRoll(EmployeeNumber, StartDate)
Note also that primary and foreign key constraint names must be unique within the database (not just in the table) - you'll need to rename the duplicate keys like fk_StartDate.
SqlFiddle here
You may also find at some point that the encumberance and additional storage requirements of composite / compound keys may make implementation of simple surrogate keys (like int identity() or Guids) a simpler approach.

SQL SMS - Error - There is already an object named "genre" in the database

I'm trying to create a hypothetical videostore database and this error message comes up everytime I execute this query:
DROP DATABASE videostore
CREATE DATABASE videostore
CREATE TABLE genre
(
genre_id INT NOT NULL PRIMARY KEY IDENTITY,
genre_name VARCHAR(15) NOT NULL
);
CREATE TABLE classification
(
rating VARCHAR(2) NOT NULL CONSTRAINT classification_pk PRIMARY KEY,
description VARCHAR(100) NOT NULL,
minimum_age INT NULL,
);
CREATE TABLE format
(
format_id INT NOT NULL CONSTRAINT format_pk PRIMARY KEY IDENTITY,
format_name VARCHAR(8) NOT NULL,
purchase_cost FLOAT NOT NULL
);
CREATE TABLE rental_cost
(
rental_cost_id INT NOT NULL CONSTRAINT rental_cost_pk PRIMARY KEY IDENTITY,
rental_name VARCHAR(15) NOT NULL,
rental_cost FLOAT NOT NULL,
rental_days TINYINT NOT NULL
);
CREATE TABLE customer
(
customer_id INT NOT NULL CONSTRAINT customer_pk PRIMARY KEY IDENTITY,
first_name VARCHAR(20) NOT NULL,
surname VARCHAR(20) NOT NULL,
dob DATETIME NOT NULL,
home_address VARCHAR(50) NOT NULL,
contact_number VARCHAR(10) NOT NULL,
referrer_id INT NULL FOREIGN KEY REFERENCES customer(customer_id),
);
CREATE TABLE movie
(
movie_id INT NOT NULL CONSTRAINT movie_pk PRIMARY KEY IDENTITY,
movie_name VARCHAR(40) NOT NULL,
year SMALLINT NOT NULL,
duration SMALLINT NULL,
descrip VARCHAR(120) NULL,
classification VARCHAR(2) NOT NULL FOREIGN KEY REFERENCES classification(rating),
rental_cost_id INT NOT NULL FOREIGN KEY REFERENCES rental_cost(rental_cost_id),
);
CREATE TABLE copy
(
copy_id INT NOT NULL CONSTRAINT copy_pk PRIMARY KEY IDENTITY,
movie_id INT NOT NULL FOREIGN KEY REFERENCES movie(movie_id),
format_id INT NOT NULL FOREIGN KEY REFERENCES format(format_id),
);
CREATE TABLE rental
(
rental_id INT NOT NULL CONSTRAINT rental_pk PRIMARY KEY IDENTITY,
copy_id INT NOT NULL FOREIGN KEY REFERENCES copy(copy_id),
customer_id INT NOT NULL FOREIGN KEY REFERENCES customer(customer_id),
rental_date DATETIME NOT NULL,
return_date DATETIME NULL
);
CREATE TABLE genre_movie
(
genre_id INT NOT NULL FOREIGN KEY REFERENCES genre(genre_id),
movie_id INT NOT NULL FOREIGN KEY REFERENCES movie(movie_id),
CONSTRAINT genre_movie_pk PRIMARY KEY (genre_id, movie_id)
);
(Sorry it's not in the correct format for reading a script with ease, I just really couldn't work out how to do that.)
Basically when I execute the SQL script it tells me that the object 'genre' already exists, but I can't see it anywhere else in my code.
And the table shouldn't already exist because I drop the database each time the script is executed right?
Sidenote - if there's a better way to make it so the database is dropped only if it exists please help me with that also.
Appreciate it.
I think you need to add USE videostore after the CREATE DATABASE videostore. Otherwise you are creating tables in whatever database you are currently in.
I think you are executing this in the context of the master database. If you check it you will probably see all your tables are actually in master.
Change the first part to this:
DROP DATABASE videostore
CREATE DATABASE videostore
USE videostore
CREATE TABLE genre
It's generally best to execute sql statements when required - try:
DROP DATABASE videostore
GO
CREATE DATABASE videostore
GO
USE videostore
CREATE TABLE genre
(
genre_id INT NOT NULL PRIMARY KEY IDENTITY,
genre_name VARCHAR(15) NOT NULL
);
GO
etc.