SQL Server 2012 : Create Table - sql

CREATE TABLE Schedule
(
Section DATETIME NOT NULL PRIMARY KEY(CourseID, Section, EmployeeID),
CourseID VARCHAR(10) REFERENCES Course(CourseID) NOT NULL,
EmployeeID VARCHAR(20) NOT NULL REFERENCES Employee(EmployeeID),
StartTime TIME NULL,
Days DATE NULL,
Length TIME NULL
)
CREATE TABLE Enrollment
(
StudentID INT Primary key (StudentID, CourseID, Section) NOT NULL,
CourseID VARCHAR(10) REFERENCES Course(CourseID) NOT NULL,
Section DATETIME NOT NULL REFERENCES Schedule(Section)
)
2nd table did not get created, where did I go wrong?

Its because you made the primary key in the Schedule table a natural/combined key.
Try creating a stand alone column for this purpose instead. I've included an example below that shows the differences.
CREATE TABLE DBO.PK_TEST (
Col_A INT NOT NULL
,Col_B INT NOT NULL
,Primary Key(Col_A,Col_B)
)
Create table DBO.PK_TEST_2 (
Col_A int NOT NULL
,Col_B int NOT NULL
,Col_C as (cast(Col_A as nvarchar)
+ cast(Col_B as nvarchar)) PERSISTED NOT NULL
,primary key(Col_C)
)

Related

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.

USing Join Information to get the information from the table

I am new to the SQL. I am learning joins in query so that i eterive the information from the table using information. I am working in this question .
Get the EmployeeNumber for the employees and the date they started any given department.
Below is my table definition :
CREATE TABLE Employees (
EmployeeID int IDENTITY(1,1) PRIMARY KEY
,EmployeeNumber int UNIQUE
,DateOfBirth datetime NOT NULL
,FirstName nvarchar(14) NOT NULL
,MiddleName nvarchar(14) NOT NULL
,LastName nvarchar(16) NOT NULL
,DateHired datetime NOT NULL
)
CREATE TABLE Customers (
CustomerID int IDENTITY(1,1) PRIMARY KEY
,FirstName nvarchar(14) NOT NULL
,MiddleName nvarchar(14) NOT NULL
,LastName nvarchar(16) NOT NULL
,DateLastVisited datetime NOT NULL
,EmailAddress nvarchar(52) NOT NULL
)
CREATE TABLE Departments (
DepartmentID int IDENTITY(1,1) PRIMARY KEY
,Code nchar(4) UNIQUE
,Name nvarchar(40) NOT NULL
)
CREATE TABLE DepartmentEmployees (
DepartmentEmployeeID int IDENTITY(1,1) PRIMARY KEY
,EmployeeID int NOT NULL
CONSTRAINT Department_Employee REFERENCES Employees(EmployeeID)
,DepartmentID int NOT NULL
CONSTRAINT Employee_Department REFERENCES Departments(DepartmentID)
,DateStarted datetime NOT NULL
,DateEnded datetime NOT NULL
)
CREATE TABLE Salaries (
SalaryID int IDENTITY(1,1) PRIMARY KEY
,EmployeeID int NOT NULL
CONSTRAINT Salaried_Employee REFERENCES Employees(EmployeeID)
,Amount money NOT NULL
,DateStarts datetime NOT NULL
,DateEnds datetime NOT NULL
)
I have added the information by inserting the data accordingly to the table.
For the question .
I have written this answer but i am not sure wether it is right or not.
SELECT e.EmployeeNumber,
d.DateStarted
FROM Employees e
Right
Join DepartmentEmployees d
on e.EmployeeID= d.DepartmentEmployeeID;
DepartmentEmployeeID is the primary key for the table department, you need to join the employee id's in both tables.
SELECT E.EmployeeNumber, D.DateStarted
FROM DepartmentEmployees D
LEFT JOIN Employees E
ON E.EmployeeID= D.EmployeeID;

How to Relate 2 table with each other with 2 foreign keys

Here is my code it generates Foreign key conflict error
CREATE TABLE tblProducts
(
ProductID int NOT NULL IDENTITY PRIMARY KEY,
ProductName nvarchar(30) NOT NULL,
BatchID int NOT NULL FOREIGN KEY REFERENCES tblBatches (BatchID)
)
CREATE TABLE tblBatches
(
BatchID INT NOT NULL IDENTITY PRIMARY KEY,
BatchCode nvarchar(20) NOT NULL,
Quantity int NOT NULL,
BatchMnf Date NOT NULL,
BatchExp Date NOT NULL,
PurchaseRate int NOT NULL,
SalesRate int NOT NULL,
ProductID int NOT NULL FOREIGN KEY REFERENCES tblProducts (ProductID)
)
You cannot do that. This is a circular reference.
This is a bad design but if you want to do that, you need to make foreign key columns Nullable.
CREATE TABLE tblProducts
(
ProductID int NOT NULL IDENTITY PRIMARY KEY,
ProductName nvarchar(30) NOT NULL,
BatchID int NULL FOREIGN KEY REFERENCES tblBatches (BatchID)
)
CREATE TABLE tblBatches
(
BatchID INT NOT NULL IDENTITY PRIMARY KEY,
BatchCode nvarchar(20) NOT NULL,
Quantity int NOT NULL,
BatchMnf Date NOT NULL,
BatchExp Date NOT NULL,
PurchaseRate int NOT NULL,
SalesRate int NOT NULL,
ProductID int NULL FOREIGN KEY REFERENCES tblProducts (ProductID)
)
Then you need to update reference fields after inserting records in tblBatches and tblProducts.
The good design says you need to create a bridge table like this:
CREATE TABLE tblProductsBatch
(
ID int NOT NULL IDENTITY PRIMARY KEY,
ProductID int NOT NULL,
BatchID int NOT NULL
)
And after inserting product and batch, you need to insert a record in this table to link rows to each other.

Error relate SQL Server tables

I have the following problem: when we run the code, it displays the following error:
There are primary keys or candidates in the reference Ticket table
that match the list of referencing columns in foreign key '
FK__Payment__PkTicke__1A14E395
Code:
create table SystemUser
(
PkUser int identity(1,1),
UserLogin nvarchar(20) not null unique,
UserPassword nvarchar(50) not null,
UserName nvarchar(50) not null,
UserCpf nvarchar(50) not null,
UserBirth datetime not null,
UserGender nvarchar(15) not null,
AddressCep int not null,
AddressStreet nvarchar(50) not null,
AddressNumber nvarchar(20) not null,
AddressComplement nvarchar(50) not null,
AddressCity nvarchar(50) not null,
AddressState nvarchar(50) not null,
primary key(PkUser)
)
create table Attractions
(
PkAttraction integer identity(1,1) ,
AttractionName nvarchar(50) not null unique,
AttractionDate datetime not null,
AttractionDescription nvarchar(150) not null
primary key(PkAttraction)
)
create table Ticket
(
PkTicket int identity(1,1),
PkUser int not null,
PkAttraction int not null,
TicketPrice decimal not null,
primary key(PkTicket, PkUser, PkAttraction),
foreign key(PkUser) references SystemUser(PkUser),
foreign key(PkAttraction) references Attractions(PkAttraction)
)
create table Payment
(
PkPayment int identity(1,1),
PkTicket int not null,
Portion int not null,
IdTransaction nvarchar(100) not null,
Payday datetime not null,
primary key(PkPayment, PkTicket),
foreign key(PkTicket) references Ticket(PkTicket),
)
create table FormPayment
(
PkFromPayment int identity(1,1),
PkPayment int not null,
ShareValue decimal not null,
ExpirationDate datetime not null
primary key(PkFromPayment, PkPayment),
foreign key(PkPayment) references Payment(PkPayment),
)
Your Ticket table as a primary key made up from 3 columns:
create table Ticket
(
.....
primary key(PkTicket, PkUser, PkAttraction),
....
)
Any table that wants to reference that table Ticket must also provide all 3 columns for the foreign key.
You cannot reference only part of a primary key - if you want to reference it, you must have all columns that it contains - otherwise you cannot establish a FK relationship.
So you must add the PkUser and PkAttraction columns to your Payment table so that you can establish this FK relationship:
create table Payment
(
PkPayment int identity(1,1),
PkTicket int not null,
PkUser int not null, // add this
PkAttraction int not null, // add this
Portion int not null,
IdTransaction nvarchar(100) not null,
Payday datetime not null,
primary key(PkPayment, PkTicket),
// change to this
foreign key(PkTicket, PkUser, PkAttraction) references Ticket(PkTicket, PkUser, PkAttraction)
.....
)
When you not specify a name for FK and PK, SQL server generates a name. in this case, looks like SQL server generates duplicate name.
If you specify name for FK and PK, it will work.

SQL Logic and Aggregate Issue

I have the following problem to solve in SQL :
d) A query that provides management information on take up of the various types of activities on offer. For each type of activity, the query should show the total number of individuals who took that type of activity and the average number of individuals taking each type of activity.
Here are my tables :
CREATE TABLE accommodations
(
chalet_number int PRIMARY KEY,
chalet_name varchar(40) NOT NULL,
no_it_sleeps number(2) NOT NULL,
indivppw number(4) NOT NULL
)
CREATE TABLE supervisors
(
supervisor_number int PRIMARY KEY,
supervisor_forename varchar(30) NOT NULL,
supervisor_surname varchar(30) NOT NULL,
mobile_number varchar(11) NOT NULL
)
CREATE TABLE visitors
(
visitor_ID int PRIMARY KEY,
group_ID int NOT NULL,
forename varchar(20) NOT NULL,
surname varchar(20) NOT NULL,
dob date NOT NULL,
gender varchar(1) NOT NULL
)
CREATE TABLE activities
(
activity_code varchar(10) PRIMARY KEY,
activity_title varchar(20) NOT NULL,
"type" varchar(20) NOT NULL
)
CREATE TABLE "groups"
(
group_ID int PRIMARY KEY,
group_leader varchar(20) NOT NULL,
group_name varchar(30)
number_in_group number(2) NOT NULL
)
CREATE TABLE bookings
(
group_ID int NOT NULL,
start_date date NOT NULL,
chalet_number int NOT NULL,
no_in_chalet number(2) NOT NULL,
start_date date NOT NULL,
end_date date NOT NULL,
CONSTRAINT bookings_pk PRIMARY KEY(group_ID, chalet_number));
CREATE TABLE schedule
(
schedule_ID int PRIMARY KEY,
activity_code varchar(10) NOT NULL,
time_of_activity number(4,2) NOT NULL,
am_pm varchar(2) NOT NULL,
"date" date NOT NULL
)
CREATE TABLE activity_bookings
(
visitor_ID int NOT NULL,
schedule_ID int NOT NULL,
supervisor_number int NOT NULL,
comments varchar(200),
CONSTRAINT event_booking_pk PRIMARY KEY(visitor_ID, schedule_ID));
ALTER TABLE visitors
ADD FOREIGN KEY (group_ID)
REFERENCES "groups"(group_ID)
ALTER TABLE Schedule
ADD FOREIGN KEY (activity_code)
REFERENCES activities(activity_code)
ALTER TABLE bookings
ADD FOREIGN KEY (group_ID)
REFERENCES "groups"(group_ID)
ALTER TABLE bookings
ADD FOREIGN KEY (chalet_number)
REFERENCES accommodations(chalet_number)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (visitor_ID)
REFERENCES visitors(visitor_ID)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (schedule_ID)
REFERENCES schedule(schedule_ID)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (supervisor_number)
REFERENCES supervisors(supervisor_number)
I have the following solution:
SELECT activities."type", 'overalltotal' AS OT, ('overalltotal' / 'activities') AS AVG
FROM activities, schedule
WHERE 'overalltotal' = (SELECT SUM(COUNT(schedule_ID))
FROM activities, schedule
WHERE schedule.activity_code = activities.activity_code
GROUP BY activities."type"
)
AND 'activities' = (SELECT COUNT(DISTINCT activities."type")
FROM activities
)
AND schedule.activity_code = activities.activity_code
GROUP BY activities."type";
I have implemented sample data and code to check the variables above:
SELECT SUM(COUNT(schedule_ID))
FROM activities, schedule
WHERE schedule.activity_code = activities.activity_code
GROUP BY activities."type";
Result : 20
SELECT COUNT(DISTINCT activities."type")
FROM activities;
Result : 5
However when running the code :
ORA-01722: invalid number
01722. 00000 - "invalid number"
*Cause:
*Action:
EDIT:
Using Dave's Code i have the following output:
Snowboarding 15
sledding 19
Snowmobiling 6
Ice Skating 5
Skiing 24
How would i do the final part of the question?
and the average number of individuals taking each type of activity.
You must use double quotes around column names in Oracle, not single quotes. For example, "overalltotal". Single quotes are for text strings, which is why you're getting an invalid number error.
EDIT: This is probably the type of query you want to use:
SELECT activities."type", COUNT(*) AS total, COUNT(*)/(COUNT(*) OVER ()) AS "avg"
FROM activities a
JOIN schedule s ON a.activity_code=s.activity_code
JOIN activity_bookings ab ON s.schedule_ID=ab.schedule_ID
GROUP BY activities."type";
Basically, because each activity booking has one visitor id, we want to get all the activity bookings for each activity. We have to go through schedule to do that. They we group the rows by the activity type and count how many activity bookings we have for each type.