How do I look at one table and use it to check another table for data integrity?
I have two SQL Tables.
One that is a person table
CREATE TABLE PERSON
(
ID INT IDENTITY(10000,1) NOT NULL,
Firstname VARCHAR(15),
Lastname VARCHAR(25) NOT NULL,
Birthdate DATE,
Gender VARCHAR(1),
CHECK ( GENDER IN ('M', 'F')),
Street VARCHAR(50),
City VARCHAR(15),
State VARCHAR(2),
CHECK (State IN ('FL','GA','PA')),
Zip INT,
Phone VARCHAR(10),
Employee VARCHAR(1),
CHECK ( Employee IN('Y','N')),
Member VARCHAR(1),
CHECK ( Member IN('Y','N')),
CHECK (Member IN ('Y') or Employee IN ('Y')),
CONSTRAINT PERSON_PK PRIMARY KEY (ID));
And Employee Table
CREATE TABLE EMPLOYEE
(
ID INT NOT NULL,
Datehired DATE DEFAULT GETDATE(),
Status VARCHAR(1),
CHECK ( Status IN ('F','C')),
Position VARCHAR(25),
EmpType VARCHAR(25),
CONSTRAINT EMPLOYEE_PK PRIMARY KEY (ID),
CONSTRAINT EMPLOYEE_PERSON_FK FOREIGN KEY (ID) REFERENCES PERSON);
Let's say someone isn't an employee. I can still insert them into the Employee Table.
INSERT INTO EMPLOYEE
(ID, Status, Position, EmpType)
VALUES
('10000','C','Teaching Classes','Instructor');
How Do I prevent this from happening.
One method is to have a redundant key:
alter table person
contraint unq_person_id_employee
unique (id, employee);
Then add a computed column to employee:
alter table employee add employee as ('Y') persisted;
Finally, add the constraint:
alter table employee
add constraint fk_employee_person
foreign key (id, employee) references person(id, employee);
Now, you are guaranteed that only employees are in the Employee table.
Related
I'm not sure where the error is,
(Error at Line 2)
(Help)
select last_name, first_name
from employee group by Employee_ID in
select Employee_ID from service group by Property_ID having count(*)>2;
employee table
create table EMPLOYEE(
Employee_ID int primary key,
Last_name char(30),
First_Name char(30),
CellPhone char(20),
ExperienceLevel char(30),
CONSTRAINT EX_EMPLOYEE_EXPERIENCELEVEL CHECK (ExperienceLevel IN('Master', 'Junior', 'Senior'))
);
service Table
create table SERVICE (
Property_ID int,
Employee_ID int,
Service_Date date,
Hours_worked int,
primary key(Property_ID, Employee_ID),
foreign key(Property_ID) references PROPERTY(Property_ID),
foreign key(Employee_ID) references EMPLOYEE(Employee_ID)
);
property table
create table PROPERTY(
Property_ID int primary key,
Owner_ID int,
Owner_Name char(30),
Owner_email char(30),
Owner_type char(30),
CONSTRAINT EX_PROPERTY_OWNERTYPE CHECK (Owner_type IN('Individual', 'Corporate', 'Partnership'))
);
Your query is not very clear. The in clause before the subquery is not a valid clause at that position. If you want to select the employes whose id are in the subquery, so you have to do something like this:
select last_name, first_name
from employee
WHERE Employee_ID in
(select Employee_ID from service
group by Property_ID having count(*)>2);
I am designing a database for school.
Requirements
Professors have an SSN, a name, an age, gender, a rank, and a research specialty
Professors work in exactly one department
Departments have a department number, a department name, and a main office
Departments must have one professor (known as the chairman) who runs the department
My current schema for "Professors" and "Departments"
CREATE DOMAIN SSN AS CHAR(11) CONSTRAINT validSSN CHECK (VALUE ~* "^\d{3}-\d{2}-\d{4}$");
CREATE TABLE Persons (
person_id INT PRIMARY KEY AUTO_INCREMENT,
ssn SSN NOT NULL CONSTRAINT mustBeDifferent UNIQUE,
name VARCHAR(255) NOT NULL,
age INT NOT NULL CONSTRAINT nonnegativeAge CHECK(age >= 0),
gender CHAR(1) CONSTRAINT mustBeMaleOrFemale CHECK(gender = "M" OR gender = "F") NOT NULL,
);
CREATE TABLE Professors (
ranking INT NOT NULL CONSTRAINT positiveRanking CHECK(ranking > 0),
research_specialty VARCHAR(255) NOT NULL,
department_id INT NOT NULL REFERENCES Departments(department_number)
) INHERITS(Persons);
CREATE TABLE Departments (
department_number INT PRIMARY KEY AUTO_INCREMENT,
department_name VARCHAR(255) NOT NULL,
main_office VARCHAR(255) NOT NULL,
chairman_id INT REFERENCES Professors(person_id)
);
I have a foreign key in the "Professors" table that references the "Departments" table and a foreign key in the "Departments" table that references the "Professors" table.
Is there any way that I could go about resolving this issue?
I see a few problems:
professors should not inherit from persons, but reference it with a foreign key.
Otherwise you cannot guarantee uniqueness of the primary key.
Don't store the age in persons, but the birthday.
Otherwise your data will grow invalid pretty quickly.
If there is no length limit dictated by the application, don't use varchar(255), but use text.
SQL Error
I'm not sure what I did wrong here
Here is the DDL I used to create my tables
Create Table HomeState (StateAbbreviation char(2) Primary Key,
StateName varchar(25));
Create Table Country (CountryAbbreviation char(2) Primary Key,
CountryName varchar(35));
Create Table Employee (EmployeeID Integer Primary Key NOT NULL,
FirstName varchar(20),
LastName varchar(30),
MI char(1),
HomeAddress varchar(30),
Zip char(5),
DateOfBirth date,
HireDate date,
TerminationDate date,
AnnualSalary number(20,2),
LicenseDate date,
StateAbbreviation char(2),
CountryAbbreviation char(2),
Foreign Key (StateAbbreviation) references HomeState,
Foreign Key (CountryAbbreviation) references Country);
Create Table Truck (VinNumber Integer Primary Key,
Make varchar(25),
Model varchar(30),
Year Integer,
PurchasePrice number(20,2),
LicenseNumber varchar(15));
Create Table EmployeeTruck (EmployeeID Integer,
VinNumber Integer,
Primary Key(EmployeeID,VinNumber),
Foreign Key (EmployeeID) references Employee,
Foreign Key (VinNumber) references Truck);
Create Table Accident (AccidentID Integer Primary Key,
DateOfAccident date,
AccidentDescription varchar(200),
AccidentLocation varchar(100),
EmployeeID Integer,
Foreign Key (EmployeeID) references Employee);
and here is the command i used to try and fill in the employee table
insert into employee
values ('1','brian','kim','j','adfasdf',
'1234','24-nov-1993','24-sep-1993','24-sep-1993',
'1234','24-sep-1993','as','as')
but it always gives me the error i put as the title of this question...
In the table "Employee", you say that Foreign Key (StateAbbreviation) references HomeState, and Foreign Key (CountryAbbreviation) references Country). The values you insert into Employee.HomeState and Employee.CountryAbbreviation have to exist in the tables HomeState and Country before you can insert into Employee.
Insert rows into HomeState and Country before you insert into Employee.
You have other problems, too. Here's an example.
Create Table HomeState (StateAbbreviation char(2) Primary Key,
StateName varchar(25));
insert into HomeState values ('AL', 'Alabama');
insert into HomeState values ('AM', 'Alabama');
insert into HomeState values ('AN', 'Alabama');
All those insert statements succeed. They shouldn't. In this case, StateName is also a candidate key.
Create Table HomeState (
StateAbbreviation char(2) Primary Key,
StateName varchar(25) not null unique
);
Let's take this a little further.
Create Table HomeState (
StateAbbreviation char(2) Primary Key,
StateName varchar(25) not null unique
);
Create Table Country (
CountryAbbreviation char(2) Primary Key,
CountryName varchar(35) not null unique
);
insert into HomeState values ('CA', 'California');
insert into Country values ('AF', 'Afghanistan');
insert into Employee (EmployeeID, StateAbbreviation, CountryAbbreviation)
values (-42, 'CA', 'AF');
The state "California, US" makes sense. The state "California, Afghanistan" doesn't.
An employee having no name doesn't make sense. Declare FirstName, LastName, and HireDate not null.
Bet on this: whatever nonsense your database allows will appear. It's just a matter of time.
I have one query that creates several tables, listed below, and a second query that is supposed to add Primary and Foreign keys to each. However, when I try executing my query, I'm greeted with the following error messages:
Msg 1776, Level 16, State 0, Line 2
There are no primary or candidate keys in the referenced table 'DEPARTMENT' that match the referencing column list in the foreign key 'FK__EMPLOYEE__dno__25869641'.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint. See previous errors.
I'm not sure what this means, as I have researched both primary and foreign keys. Can anyone lead me in the right direction as to how to solve this issue? Thanks! :)
CREATE TABLE EMPLOYEE
(
fname varchar(100),
minit char(1),
lname varchar(100),
ssn char(9),
bdate date,
addr varchar(100),
sex char(1),
salary int,
super_ssn char(9),
dno int
);
CREATE TABLE DEPARTMENT
(
dname varchar(100),
dnumber int,
mgr_ssn char(9),
mgr_start_date date
);
CREATE TABLE DEPENDENTS
(
essn char(9),
dependent_name varchar(100),
sex char(1),
bdate date,
relationship varchar(100)
);
CREATE TABLE DEPT_LOCATIONS
(
dnumber int,
dlocation varchar(100)
);
CREATE TABLE PROJECT
(
pname varchar(100),
pnumber int,
plocation varchar(100),
dnum int
);
CREATE TABLE WORKS_ON
(
essn char(9),
pno int,
hrs float
);
ALTER TABLE EMPLOYEE ADD PRIMARY KEY(ssn);
ALTER TABLE EMPLOYEE ADD FOREIGN KEY(super_ssn) REFERENCES EMPLOYEE(ssn);
ALTER TABLE EMPLOYEE ADD FOREIGN KEY(dno) REFERENCES DEPARTMENT(dnumber);
ALTER TABLE DEPARTMENT ADD PRIMARY KEY(dnumber);
ALTER TABLE DEPARTMENT ADD FOREIGN KEY(mgr_ssn) REFERENCES EMPLOYEE(ssn);
ALTER TABLE DEPT_LOCATIONS ADD PRIMARY KEY(dnumber, dlocation);
ALTER TABLE DEPT_LOCATIONS ADD FOREIGN KEY(dnumber) REFERENCES DEPARTMENT(dnumber);
ALTER TABLE PROJECT ADD PRIMARY KEY(pnumber);
ALTER TABLE PROJECT ADD FOREIGN KEY(dnum) REFERENCES DEPARTMENT(dnumber);
ALTER TABLE WORKS_ON ADD PRIMARY KEY(essn, pno);
ALTER TABLE WORKS_ON ADD FOREIGN KEY(essn) REFERENCES EMPLOYEE(ssn);
ALTER TABLE WORKS_ON ADD FOREIGN KEY(pno) REFERENCES PROJECT(pnumber);
ALTER TABLE DEPENDENTS ADD PRIMARY KEY(essn, dependent_name);
ALTER TABLE DEPENDENTS ADD FOREIGN KEY(essn) REFERENCES EMPLOYEE(ssn);
Primary key column should be non null able. Table definition should have not null for all PKs.
CREATE TABLE EMPLOYEE (
fname varchar(100),
minit char(1),
lname varchar(100),
ssn char(9) not null,
bdate date,
addr varchar(100),
sex char(1),
salary int,
super_ssn char(9),
dno int
);
CREATE TABLE DEPARTMENT (
dname varchar(100),
dnumber int not null,
mgr_ssn char(9),
mgr_start_date date
);
CREATE TABLE DEPENDENTS (
essn char(9) not null,
dependent_name varchar(100) not null,
sex char(1),
bdate date,
relationship varchar(100)
);
CREATE TABLE DEPT_LOCATIONS (
dnumber int not null,
dlocation varchar(100) not null
);
CREATE TABLE PROJECT (
pname varchar(100),
pnumber int not null,
plocation varchar(100),
dnum int
);
CREATE TABLE WORKS_ON (
essn char(9) not null,
pno int not null,
hrs float
);
ALTER TABLE EMPLOYEE ADD PRIMARY KEY(ssn);
ALTER TABLE DEPARTMENT ADD PRIMARY KEY(dnumber);
ALTER TABLE EMPLOYEE ADD FOREIGN KEY(super_ssn) REFERENCES EMPLOYEE(ssn);
ALTER TABLE EMPLOYEE ADD FOREIGN KEY(dno) REFERENCES DEPARTMENT(dnumber);
ALTER TABLE DEPARTMENT ADD FOREIGN KEY(mgr_ssn) REFERENCES EMPLOYEE(ssn);
ALTER TABLE DEPT_LOCATIONS ADD PRIMARY KEY(dnumber, dlocation);
ALTER TABLE DEPT_LOCATIONS ADD FOREIGN KEY(dnumber) REFERENCES DEPARTMENT(dnumber);
ALTER TABLE PROJECT ADD PRIMARY KEY(pnumber);
ALTER TABLE PROJECT ADD FOREIGN KEY(dnum) REFERENCES DEPARTMENT(dnumber);
ALTER TABLE WORKS_ON ADD PRIMARY KEY(essn, pno);
ALTER TABLE WORKS_ON ADD FOREIGN KEY(essn) REFERENCES EMPLOYEE(ssn);
ALTER TABLE WORKS_ON ADD FOREIGN KEY(pno) REFERENCES PROJECT(pnumber);
ALTER TABLE DEPENDENTS ADD PRIMARY KEY(essn, dependent_name);
ALTER TABLE DEPENDENTS ADD FOREIGN KEY(essn) REFERENCES EMPLOYEE(ssn);
I have created table Employee
Create table Employee
(
FName varchar(20) Not Null,
LName varchar(20) Not Null,
SSN int Not Null,
BDate Datetime,
Address varchar(50),
Sex char(1),
Salary money,
Super_SSN int,
Primary Key(SSN),
Foreign Key(Super_SSN) references Employee(SSN)
)
When i try to insert first row to ,
insert into Employee(FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
values('John','Smith',12345,'1965-01-09','Houston,TX','M',30000,33344)
I am getting the error like..
Error:
The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Employee_Employee". The conflict occurred in database "Company", table "dbo.Employee", column 'SSN'.
You need to first INSERT record for SSN '33344' with Super_SSN value as NULL.
INSERT INTO Employee(FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
VALUES (<FName>,<LName>,'33344',<BDate>,<Address>,<Sex>,<Salary>,NULL)
After that insert
INSERT INTO Employee (FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
VALUES ('John','Smith',12345,'1965-01-09','Houston,TX','M',30000,33344)
If SSN '33344' have any Super_SSN, update the SSN value (this record should be available in table).
The error is likely thrown because there is a foreign key from Super_SSN to SSN column. You cannot insert a value of 33344 into Super_SSN unless that value already exists in SSN. Try inserting null into Super_SSN or inserting user 33344 first.