How to create tables using below statement - sql-server

Working on small ASP.Net MVC project, and got requirement from business analyst who gave me PDF file with below SQL staff to create in database.
Looking on how to achieve result from the below SQL question.
By the way should all be created using T-SQL
Student - Table
studentNo Identity column INT NOT NULL PK
lastName VARCHAR(30) NOT NULL
firstName VARCHAR(30) NOT NULL
gender CHAR NOT NULL
phoneNumber VARCHAR(20) NOT NULL
salaryAmount INT,
departmentID INT FK
Department - Table
departmentID Identity Column INT NOT NULL PK
name VARCHAR(40) NOT NULL
priceCentreID INT FK
PriceCentre - Table
priceCentreID
name VARCHAR(50)
accountID varchar(50)

As I understand you want help to create the sql code to generate the tables you provided?
Below is the code to create the tables and the relations that you are looking for.
code:
CREATE TABLE PriceCentre(
priceCenterID INT PRIMARY KEY,
name VARCHAR(50),
accountID VARCHAR(50)
);
GO
CREATE TABLE Department(
departmentID INT NOT NULL PRIMARY KEY,
name VARCHAR(40) NOT NULL,
priceCenterID int FOREIGN KEY REFERENCES PriceCentre (priceCenterID)
)
GO
CREATE TABLE Student(
studentNo INT NOT NULL PRIMARY KEY,
lastName VARCHAR(30) NOT NULL,
firstName VARCHAR(30) NOT NULL,
gender CHAR NOT NULL,
phoneNumber VARCHAR(20) NOT NULL,
salaryAmount INT,
departmentID INT FOREIGN KEY REFERENCES Department(departmentID)
);

Related

Postgresql Trying to implement One-To-Many

this is my first hands-on experience with Sql and I'm trying to construct One-To-Many relationship, here is the SQL code:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL,
cars_owning INT[] REFERENCES car(id)
);
and I get this error:
Key columns "cars_owning" and "id" are of incompatible types: integer[] and integer.
Here is the model a person can have many cars but each car have only one owner
typically (as a good general rule of thumb) the many refers to the one. not the other way around as you have tried.
So, alter the schema as:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL,
owner_id BIGINT FOREIGN KEY REFERENCES person(id)
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL
);
If you need to get the list of cars owned by a person, use this select statement
SELECT person.id, ARRAY_AGG(car.id) owns_car_ids
FROM person
LEFT JOIN car ON person.id = car.owner_id
GROUP BY 1

i need Database table creating

i created my tables and I'm stuck at the last one,
here is the tables that been created correctly
CREATE TABLE Staff (
Staff_ID INT NOT NULL PRIMARY KEY,
First_Name VARCHAR(50),
Last_Name VARCHAR(50),
Username VARCHAR(10),
Password VARCHAR(10),
Address VARCHAR(30)
)
CREATE TABLE Category (
Category_ID INT NOT NULL PRIMARY KEY,
Name VARCHAR(30)
)
CREATE TABLE Author (
Author_ID INT NOT NULL PRIMARY KEY,
First_Name VARCHAR(50),
Last_Name VARCHAR(50),
Birth_Place VARCHAR(30),
Birth_Date DATE
)
CREATE TABLE Publisher (
Publisher_ID INT NOT NULL PRIMARY KEY,
Name VARCHAR(50)
)
and this is the one I'm getting an error :
CREATE TABLE Book (
Book_ID INT NOT NULL PRIMARY KEY,
Title VARCHAR(50),
Edition INT(30),
Year_Published INT(4),
FOREIGN KEY (Publisher_ID) REFERENCES Publisher(Publisher_ID),
FOREIGN KEY (Author_ID) REFERENCES Author(Author_ID),
FOREIGN KEY (Category_ID) REFERENCES Category(Category_ID)
)
the error says:
"ORA-00907: missing right parenthesis"
INT can not have a scale associated with it so YEAR_PUBLISHED and EDITION are incorrect definitions.
I believe that, generally, you would be better off sticking to NUMBER for numeric datatypes, eg NUMBER(4), NUMBER(30).
In the database the INT datatype is simply a sub-type of NUMBER so you aren't gaining anything by using it:
type NUMBER is NUMBER_BASE;
subtype INTEGER is NUMBER(38,0);
subtype INT is INTEGER;
If you want to see the definitions for the various 'other' numeric datatypes take a look at the SYS.STANDARD package.
The INT data type does not have a precision.
You also need to define the Publisher_ID, Author_ID and Category_ID columns.
It is good practice to name your constraints.
A PRIMARY KEY column is both NOT NULL and UNIQUE so you do not need to include a second NOT NULL constraint.
Like this:
CREATE TABLE Book (
Book_ID INT CONSTRAINT Book__Book_id__PK PRIMARY KEY,
Title VARCHAR(50),
Edition INT,
Year_Published INT,
Publisher_ID INT CONSTRAINT Book__Publisher_ID__FK REFERENCES Publisher(Publisher_ID),
Author_ID INT CONSTRAINT Book__Author_id__FK REFERENCES Author(Author_ID),
Category_ID INT CONSTRAINT Book__category_ID__FK REFERENCES Category(Category_ID)
);

Using the last inserted record's ID as a foreign key

I am making a database which links together two tables via the primary key of the first table. The one with the primary key which links the two is created first but how do i make the second record get the ID of the record I just created?
create table Person
(
Person_ID int IDENTITY(100000,1) primary key,
First_Name varchar(20) not null,
Last_Name varchar(20) not null,
)
create table Employee
(
Employee_ID int identity(100000,1) primary key,
Person_ID int references Person(Person_ID),
Employee_Type varchar(10)
)
insert into Person(First_Name, Last_Name) values ('Michael', 'Chu');
insert into Employee(Person_ID, Employee_Type,) values (????????, 'Admin');
I've had a look at the 'last()' function but not really sure how to utilise that. Other then that, I have no idea. Can someone help me out or guide me in the right direction.
try this:
create table Person
(
Person_ID int IDENTITY(100000,1) primary key,
First_Name varchar(20) not null,
Last_Name varchar(20) not null,
)
create table Employee
(
Employee_ID int identity(100000,1) primary key,
Person_ID int references Person(Person_ID),
Employee_Type varchar(10)
)
DECLARE #myID AS INT
insert into Person(First_Name, Last_Name) values ('Michael', 'Chu');
SET #myID = ##IDENTITY
insert into Employee(Person_ID, Employee_Type,) values (#myID , 'Admin');

Database schema for a school

Here is the database query needed to create the database:
create table Area
(
AreaId int primary key identity(1,1),
Name nvarchar(64) not null
)
create table Level
(
LevelId int primary key identity(1,1),
Name nvarchar(32) not null,
Principle nvarchar(512) not null
)
create table Subject
(
SubjectId int primary key identity(1,1),
AreaId int foreign key references Area(AreaId),
LevelId int foreign key references Level(LevelId),
Name nvarchar(32) not null,
Abbreviation nvarchar(16)
)
create table StaffType
(
StaffTypeId int primary key identity(1,1),
Name nvarchar(64) not null
)
create table Staff
(
StaffId int primary key identity(1,1),
StaffTypeId int foreign key references StaffType(StaffTypeId),
Name nvarchar(128) not null,
LastNameFather nvarchar(256) not null,
LastNameMother nvarchar(256) not null,
DateOfBirth datetime,
PlaceOfBirth nvarchar(256),
Sex nvarchar(8) not null,
Carnet nvarchar(64),
Telephone nvarchar(64),
MobilePhone nvarchar(64),
Address nvarchar(256),
FatherName nvarchar(256),
MotherName nvarchar(256),
FatherContactNumber nvarchar(64),
MotherContactNumber nvarchar(64),
FatherPlaceOfWork nvarchar(64),
MotherPlaceOfWork nvarchar(64),
DateOfHiring datetime,
YearsOfService int,
Formation nvarchar(128)
)
create table Grade
(
GradeId int primary key identity(1,1),
Name nvarchar(32) not null,
LevelId int foreign key references Level(LevelId),
Observation nvarchar(256)
)
create table GradeInstance
(
GradeInstanceId int primary key identity(1,1),
StaffId int foreign key references Staff(StaffId),
GradeId int foreign key references Grade(GradeId),
Name nvarchar(32) not null,
Year datetime
)
create table Student
(
StudentId int primary key identity(1,1),
RUDE int,
Name nvarchar(64) not null,
LastNameFather nvarchar(256) not null,
LastNameMother nvarchar(256) not null,
DateOfBirth datetime not null,
PlaceOfBirth nvarchar(128),
Sex nvarchar(8),
Carnet nvarchar(32),
Telephone nvarchar(64),
MobilePhone nvarchar(64),
Address nvarchar(256),
FatherName nvarchar(512),
MotherName nvarchar(512),
FatherMobilePhone nvarchar(64),
MotherMobilePhone nvarchar(64),
FatherProfession nvarchar(64),
MotherProfession nvarchar(64),
FatherPlaceOfWork nvarchar(256),
MotherPlaceOfWork nvarchar(256),
Observations nvarchar(3000)
)
create table StudentInstance
(
StudentInstanceId int primary key identity(1,1),
GradeInstanceId int foreign key references GradeInstance(GradeInstanceId),
StudentId int foreign key references Student(StudentId)
)
create table StudentGradeReport
(
StudentGradeReportId int primary key identity(1,1),
StudentInstanceId int foreign key references StudentInstance(StudentInstanceId),
SubjectId int foreign key references Subject(SubjectId),
FirstTrimester int,
SecondTrimester int,
ThirdTrimester int,
FinalGrade int
)
If you find an attribute that should be null checked, please disregard it. I've gone over this with the client and they want certain things to left blank if so chosen by the end user.
My main concern when designing this database was how to associate a student with a grade here and now, yet keep a record for previous years and manage to see what grade he got back in 2009. See?
I think I've done a good job but you never know - the hivemind here will probably find a flaw and I'd love some feedback.
No longer using SQLite, but MSSQL.
I've tried to normalize the database as much as I could, but not religiously, just as much as it took to make it 'click'.
Before a Student, was directly related to a Classroom (Grade) instance. Now I create 'instances' of Students and assign them to a Classroom (Grade) instance. Each instance has a date saying which year it belongs to. This helps me keep a record of previous years without dirty hacks.
create table Area
(
AreaId int primary key identity(1,1),
Name nvarchar(64) not null
)
"Name" should be UNIQUE.
create table Level
(
LevelId int primary key identity(1,1),
Name nvarchar(32) not null,
Principle nvarchar(512) not null
)
"Name" should be UNIQUE.
create table Subject
(
SubjectId int primary key identity(1,1),
AreaId int foreign key references Area(AreaId),
LevelId int foreign key references Level(LevelId),
Name nvarchar(32) not null,
Abbreviation nvarchar(16)
)
Odds are good that one or more of these apply. Impossible to tell without representative sample data.
The set {AreaId, LevelId} should be
UNIQUE.
"Name" should be UNIQUE.
"Abbreviation" should be UNIQUE.
I'm running out of time.
create table StaffType
(
StaffTypeId int primary key identity(1,1),
Name nvarchar(64) not null
)
"Name" should be UNIQUE.
More later if I have time.

What is the proper procedure when trying to test your database in SQL?

I'm pretty new to databases and I have this assignment that I've completed where I had to look at a merged Entity Relationship Diagram and then create Drop Tables, Tables (with constraints and identity's), Alterations and Indexes. I'm pretty sure I've coded everything correctly but the only area I'm a little unsure about, it's how to test that the database will actually function when executing it. My instructor gave me a TestData.sql file that I just have to refer to the database and then execute and it should insert all the data into the tables and drop everything correctly. I have it all hooked up properly on SQL Server Management Studio but I forget what steps I should be taking in order to test the proper execution of the tables. I'll post some of my code so you guys can take a look. Any information regarding this issue would be greatly appreciated!
Also, when it says in the Test Data SQL code "IMPORTANT! If you need to run this script more than once you must drop and recreate your tables first to reset the identity properties." --Does this mean that if I run into any errors while trying to execute the test data, I will have to execute the DROP TABLES first and then maybe copy and paste all the TABLES back into the Database file? I don't actually have to manually type all the TABLES again, just need to re-enter them as "new" so the system will kind of reset it's identity properties?
If you guys need me to post more of the code for clarification, just let me know. Thanks for taking the time to read this :)
Update: I'm getting 2 error messages when trying to execute the TestData script: "Invalid object name 'SaleDetail'." and "Invalid object name 'Author'." I've also provided the rest of the code from my Database script file for you to take a look at. I'm almost certain everything is correct.
Database Tables Code (this is the complete code script)
USE Lab2A_BooksGalore
GO
/*------ Drop Table Statements ------*/
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'SaleDetail')
DROP TABLE SaleDetail
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'AuthorTitle')
DROP TABLE AuthorTitle
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Title')
DROP TABLE Title
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Publisher')
DROP TABLE Publisher
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Category')
DROP TABLE Category
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Author')
DROP TABLE Author
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Sale')
DROP TABLE Sale
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Employee')
DROP TABLE Employee
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Customer')
DROP TABLE Customer
/*------- Create Table Statements -------*/
CREATE TABLE Customer
(
CustomerNumber int
CONSTRAINT PK_Customer_CustomerNumber
PRIMARY KEY
IDENTITY (1, 1) NOT NULL,
LastName varchar(30) NOT NULL,
FirstName varchar(30) NOT NULL,
[Address] varchar(40) NULL,
City varchar(30) NULL,
Province char(2)
CONSTRAINT DF_Customer_Province
DEFAULT ('AB') NULL,
PostalCode char(6)
CONSTRAINT CK_Customer_PostalCode
CHECK (PostalCode LIKE '[A-Z][0-9][A-Z][0-9][A-Z][0-9]')
NULL,
HomePhone char(10)
)
CREATE TABLE Employee
(
EmployeeNumber int
CONSTRAINT PK_Employee_EmployeeNumber
PRIMARY KEY
IDENTITY (300, 1) NOT NULL,
[SIN] char(9) NOT NULL,
LastName varchar(30) NOT NULL,
FirstName varchar(30) NOT NULL,
[Address] varchar(40) NULL,
City varchar(20) NULL,
Province char(2)
CONSTRAINT DF_Employee_Province
DEFAULT ('AB') NULL,
PostalCode char(6)
CONSTRAINT CK_Employee_PostalCode
CHECK (PostalCode LIKE '[A-Z][0-9][A-Z][0-9][A-Z][0-9]')
NULL,
HomePhone char(10) NULL,
WorkPhone char(10) NULL,
Email varchar(40) NULL,
)
CREATE TABLE Sale
(
SaleNumber int
CONSTRAINT PK_Sale_SaleNumber
PRIMARY KEY
IDENTITY (3000, 1) NOT NULL,
SaleDate datetime NOT NULL,
CustomerNumber int
CONSTRAINT FK_Sale_CustomerNumber_Customer_CustomerNumber
FOREIGN KEY REFERENCES Customer(CustomerNumber)
NOT NULL,
EmployeeNumber int
CONSTRAINT FK_Sale_EmployeeNumber_Employee_EmployeeNumber
FOREIGN KEY REFERENCES Employee(EmployeeNumber)
NOT NULL,
Subtotal money
CONSTRAINT CK_Sale_Subtotal
CHECK (Subtotal <= Total) NOT NULL,
GST money NOT NULL,
Total money
CONSTRAINT CK_Sale_Total
CHECK (Total >= Subtotal) NOT NULL,
)
CREATE TABLE Author
(
AuthorCode int
CONSTRAINT PK_Author_AuthorCode
PRIMARY KEY
IDENTITY (100, 1) NOT NULL,
LastName varchar(30) NOT NULL,
FirstName varchar(30) NOT NULL,
)
CREATE TABLE Category
(
CategoryCode int
CONSTRAINT PK_Category_CategoryCode
PRIMARY KEY
IDENTITY (1, 1) NOT NULL,
[Description] varchar(40) NOT NULL,
)
CREATE TABLE Publisher
(
PublisherCode int
CONSTRAINT PK_Publisher_PublisherCode
PRIMARY KEY
IDENTITY (200, 1) NOT NULL,
[Name] varchar(40) NOT NULL,
)
CREATE TABLE Title
(
ISBN char(10)
CONSTRAINT PK_Title_ISBN
PRIMARY KEY NOT NULL,
Title varchar(40) NOT NULL,
SuggestedPrice smallmoney
CONSTRAINT DF_Title_SuggestedPrice
DEFAULT (0) NOT NULL,
NumberInStock smallint
CONSTRAINT CK_Title_NumberInStock
CHECK (NumberInStock >= 0)
CONSTRAINT DF_Title_NumberInStock
DEFAULT (0) NOT NULL,
PublisherCode int
CONSTRAINT FK_Title_PublisherCode_Publisher_PublisherCode
FOREIGN KEY REFERENCES Publisher(PublisherCode)
NOT NULL,
CategoryCode int
CONSTRAINT FK_Title_CategoryCode_Category_CategoryCode
FOREIGN KEY REFERENCES Category(CategoryCode)
NOT NULL,
)
CREATE TABLE AuthorTitle
(
ISBN char(10)
CONSTRAINT FK_AuthorTitle_ISBN_Title_ISBN
FOREIGN KEY REFERENCES Title(ISBN)
NOT NULL,
AuthorCode int
CONSTRAINT FK_AuthorTitle_AuthorCode_Author_AuthorCode
FOREIGN KEY REFERENCES Author(AuthorCode)
NOT NULL,
)
CREATE TABLE SaleDetail
(
SaleNumber int
CONSTRAINT FK_SaleDetail_SaleNumber_Sale_SaleNumber
FOREIGN KEY REFERENCES Sale(SaleNumber)
NOT NULL,
ISBN char(10)
CONSTRAINT FK_SaleDetail_ISBN_Title_ISBN
FOREIGN KEY REFERENCES Title(ISBN)
NOT NULL,
SellingPrice money NOT NULL,
Quantity int NOT NULL,
Amount money NOT NULL,
)
/*----------------- Alter Table Statements --------------------*/
---1) Add a char(10) attribute named WorkPhone to the Customer Table
ALTER TABLE Customer
ADD WorkPhone char(10) NULL
GO
---2) Add a varchar(30) attribute named Email to the Customer Table
ALTER TABLE Customer
ADD Email varchar(30) NULL
GO
---3) Add a constraint to make sure the correct format is followed for the Email attribute
ALTER TABLE Customer
ADD CONSTRAINT CK_Customer_Email
CHECK (Email LIKE '[a-z, 0-9][a-z, 0-9][a-z, 0-9]%#[a-z, 0-9][a-z, 0-9][a-z, 0-9]%.[a-z, 0-9][a-z, 0-9]%')
--- Match For: b 8 l # g v t . c a
GO
---4) Add a char(1) attribute named Active that's required for the Employee Table
ALTER TABLE Employee
ADD Active char(1) NOT NULL
GO
---5) Add a constraint to make sure the default character is used for the Active attribute
ALTER TABLE Employee
ADD CONSTRAINT DF_Employee_Active
DEFAULT ('y')
GO
/*------------------ Foreign Key Index Statements -----------------*/
CREATE NONCLUSTERED INDEX IX_Sale_CustomerNumber
ON Sale (CustomerNumber)
CREATE NONCLUSTERED INDEX IX_Sale_EmployeeNumber
ON Sale (EmployeeNumber)
CREATE NONCLUSTERED INDEX IX_Title_PublisherCode
ON Title (PublisherCode)
CREATE NONCLUSTERED INDEX IX_Title_CategoryCody
ON Title (CategoryCode)
CREATE NONCLUSTERED INDEX IX_AuthorTitle_ISBN
ON AuthorTitle (ISBN)
CREATE NONCLUSTERED INDEX IX_AuthorTitle_AuthorCode
ON AuthorTitle (AuthorCode)
CREATE NONCLUSTERED INDEX IX_SaleDetail_SaleNumber
ON SaleDetail (SaleNumber)
CREATE NONCLUSTERED INDEX IX_SaleDetail_ISBN
ON SaleDetail (ISBN)
GO
Test Data Code(this is only a snippet being this script is 100% accurate - provided by instructor)
USE Lab2A_BooksGalore
GO
--Lab 2 insert script
--IMPORTANT! If you need to run this script more than once you must drop and recreate your tables first to reset the identity properties.
--Delete existing data in the tables, if there is any
Delete From SaleDetail
Delete From Sale
Delete From AuthorTitle
Delete From Title
Delete From Employee
Delete From Customer
Delete From Category
Delete From Publisher
Delete From Author
Go
Insert into Author
(LastName, FirstName)
Values
('Smith', 'Sammy'),
('Greens', 'George'),
('Jones', 'Johnny'),
('Davidson', 'David'),
('Robertson', 'Rob'),
('Abbots', 'Abe'),
('Bakers', 'Bob'),
('Caters', 'Clem'),
('Semenko', 'Dave'),
('Franky', 'Fran'),
('Horton', 'Harry'),
('Kelly', 'Kevin'),
('Lambert', 'Larry'),
('Johnson', 'Jon'),
('Anderson', 'Ander'),
('Peterson', 'Peter'),
('Jensen', 'Jens'),
('Issacsen', 'Issac')
Insert into Publisher
(Name)
Values
('Addison Westley'),
('SAMS'),
('Harlequin'),
('Self Publish Inc'),
('Microsoft Press'),
('Jones and Bartlett'),
('WROX'),
('West'),
('Premier')
Insert into Category
(Description)
Values
('Computers'),
('Business'),
('Human Relation'),
('Electronics'),
('Designs'),
('Miscellaneous'),
('Media Design'),
('Information Technologies')

Resources