SQL Creating table Employee Department Grade - sql-server

create database staff_management;
use staff_management;
create table Employee
(
eID int(100) NOT NULL IDENTITY(1,1) PRIMARY KEY,
eName varchar(255) NOT NULL,
Job text NOT NULL,
Salary int(100) NOT NULL,
Comm int(100),
hDate date NOT NULL,
dID int(10) NOT NULL,
constraint emp_pk primary key (eID)
);
alter table Employee IDENTITY(1,1) PRIMARY KEY=1001;
alter table Employee
add column Mgr int(100) after eName;
insert into Employee(eName,Mgr, Job, Salary, Comm, hDate, dID)
values( "ken Adams", 1004, "Salesman", 70000, 20000, "2008-04-12", 1),
("Ru Jones", 1004, "Salesman", 65000, 15000, "2010-01-18", 1),
( "Dhal Sim", 1006, "Accountant", 88000, NULL, "2001-03-07", 2),
( "Ellen Honda", 1006, "Manager", 118000, NULL, "2001-03-17", 1),
( "Mike Bal", 1006, "Receptionist", 68000, NULL, "2006-06-21", 3),
( "Martin Bison",NULL, "CEO", 210000, NULL, "2010-07-12", 3),
( "Shen Li", 1004, "Salesman", 86000, 18000, "2014-09-18", 1),
( "Zang Ross", 1004, "Salesman", 65000, 10000, "2017-02-02", 1),
( "Sagar Kahn", 1004, "Salesman", 70000, 15000, "2016-03-01", 1);
alter table Employee
add constraint emp_mgr_fk foreign key (Mgr) references Employee(eID) on update cascade on delete set NULL;
create table Department
(
dID int(10) NOT NULL unique IDENTITY(1,1) PRIMARY KEY,
dName varchar(255) not null,
Address text,
phone text,
constraint d_pk primary key (dID)
);
alter table Employee
add constraint emp_d_fk
foreign key (dID) references Department(dID);
create table Grade
(
gID char(10) not null unique,
MinSal int(100),
MaxSal int(100),
Leavee int(10),
constraint g_pk primary key (gID)
);
INSERT INTO Grade (gID, MinSal, MaxSal, Leavee)
VALUES ('A', NULL, 60000, 20),
('B', 60000, 80000, 20),
('C', 80000, 100000, 20),
('D', 100000, 120000, 25),
('E', 120000, NULL, 30);
select * from Grade;
insert into Department (dName, Address, phone)
values("Sales", "Sydney", "0425 198 053"),
("Accounts", "Melbourne", "0429 198 955"),
("Admin", "Melbourne", "0428 198 758"),
("Marketing", "Sydney", "0427 198 757");
select * from Department;
I'm issue with my code
Msg 156, Level 15, State 1, Line 18
Incorrect syntax near the keyword 'IDENTITY'.
Msg 156, Level 15, State 1, Line 21
Incorrect syntax near the keyword 'column'.

The syntax for SQL Server is NOT auto_increment - you need to use an INT IDENTITY column instead. And also: in T-SQL an INT is an INT is an INT - no "precision" can be defined):
Instead of this:
create table Employee
(
eID int(100) NOT NULL auto_increment,
use this:
CREATE TABLE dbo.Employee
(
eID INT NOT NULL IDENTITY(1,1),

This question is posted under SQL-Server which is Microsoft not MySQL but your syntax appears to be for MySQL.
If you are running MSSQL the code below will work but you need to look at your foreign keys as you are trying to make a foreign key for a column on the same table. Normally when a key is introduced it is in relation to another table. I.E.the FK on Grade references the PK on Employee.
create database staff_management;
use staff_management;
create table Employee
(
eID int NOT NULL IDENTITY(1,1) PRIMARY KEY,
eName varchar(255) NOT NULL,
Job text NOT NULL,
Salary int NOT NULL,
Comm int,
hDate date NOT NULL,
dID int NOT NULL,
);
alter table Employee
add Mgr int;
insert into Employee(eName,Mgr, Job, Salary, Comm, hDate, dID)
values ('ken Adams', 1004, 'Salesman', 70000, 20000, '2008-04-12', 1),
('Ru Jones', 1004, 'Salesman', 65000, 15000, '2010-01-18', 1),
('Dhal Sim', 1006, 'Accountant', 88000, NULL, '2001-03-07', 2),
('Ellen Honda', 1006, 'Manager', 118000, NULL, '2001-03-17', 1),
('Mike Bal', 1006, 'Receptionist', 68000, NULL, '2006-06-21', 3),
('Martin Bison',NULL, 'CEO', 210000, NULL, '2010-07-12', 3),
('Shen Li', 1004, 'Salesman', 86000, 18000, '2014-09-18', 1),
('Zang Ross', 1004, 'Salesman', 65000, 10000, '2017-02-02', 1),
('Sagar Kahn', 1004, 'Salesman', 70000, 15000, '2016-03-01', 1);
--alter table Employee
--add constraint emp_mgr_fk
-- foreign key (Mgr) references Employee(eID)
-- on update cascade on delete set NULL;
create table Department
(
dID int NOT NULL IDENTITY(1,1) PRIMARY KEY,
dName varchar(255) not null,
Address text,
phone text,
);
--alter table Employee
--add constraint emp_d_fk
--foreign key (dID) references Department(dID);
create table Grade
(
gID char(10) not null unique,
MinSal int,
MaxSal int,
Leavee int,
constraint g_pk primary key (gID)
);
INSERT INTO Grade (gID, MinSal, MaxSal, Leavee)
VALUES ('A', NULL, 60000, 20),
('B', 60000, 80000, 20),
('C', 80000, 100000, 20),
('D', 100000, 120000, 25),
('E', 120000, NULL, 30);
select * from Grade;
insert into Department (dName, Address, phone)
values ('Sales', 'Sydney', '0425 198 053'),
('Accounts', 'Melbourne', '0429 198 955'),
('Admin', 'Melbourne', '0428 198 758'),
('Marketing', 'Sydney', '0427 198 757');
select * from Department;

Related

INSERT statement conflicted with the FOREIGN KEY constraint? I tried to insert data in the table ''customer'' but I always got this error

So I tried to insert data in the ''customer'' table but I always get this certain error (at the bottom).
Can anyone pinpoint if I miss anything or if it's lacking?
create table rooms
(
roomid int identity(1,1) primary key,
roomNo varchar(250) not null unique,
roomType varchar(250) not null,
bed varchar(250) not null,
price bigint not null,
booked varchar(50) default 'NO'
);
insert into rooms (roomNo, roomType, bed, price) values (010, 'Studio with AC', 'Single', '1000');
create table customer
(
cid int identity(1,1) primary key,
cname varchar(250) not null,
mobile bigint not null,
nationality varchar(250) not null,
gender varchar(50) not null,
dob varchar(50) not null,
idproof varchar(50) not null,
addres varchar(250) not null,
checkIn varchar(250) not null,
checkOut varchar(250),
chekOut varchar(250) not null default 'NO',
roomid int foreign key references rooms(roomid)
);
insert into customer (cname,mobile,nationality,gender,dob,idproof,addres,checkIn,customer.roomid) values ('Kayano Ai', 09238400394, 'Japanese', 'Female', '01-02-1998', '8923giaf', 'Somewhere', 'YES', 20);
the error notif I got is
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__customer__roomid__1F98B2C1". The conflict occurred in database "myHotel", table "dbo.rooms", column 'roomid'.
When you enter row into your customer table, customer.roomid should exist in the rooms table first.
Fist make sure the room exists or insert a new room.
INSERT INTO rooms ( roomid,roomNo, ...) VALUES (1,'room1',...);
Then insert into customer with an custormer.roomid that exists in the room table (1 in the example)
INSERT INTO customer ( cid,cname,roomid ...) VALUES (15,'customer name',1,...);

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object - SQL Server - simple table

I've had a look at some of the other answers to this kind of question, but as a beginner, they didn't quite make sense.
Could someone please advise what I'd need to change in the queries below to prevent the error
Violation of PRIMARY KEY constraint 'PK__Coding_I__C2232422662DE1EF'. Cannot insert duplicate key in object 'dbo.Coding_Interview'. The duplicate key value is (1)
Thanks in advance.
create database Interview_Questions
CREATE TABLE Coding_Interview
(
employee_id INT NOT NULL,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
gender VARCHAR(30) NOT NULL,
position VARCHAR(30) NOT NULL,
department_id INT NOT NULL,
salary INT NOT NULL,
PRIMARY KEY (department_id),
UNIQUE (employee_id)
);
INSERT INTO Coding_Interview
(employee_id, first_name, last_name, gender, position, department_id, salary)
VALUES
(2002, 'Super', 'Man', 'M', 'Tester', 1, 75000 ),
(2003, 'Jessica', 'Liyers', 'F', 'Architect', 1, 60000 ),
(2004, 'Bonnie', 'Adams', 'F', 'Project Manager', 1, 80000),
(2005, 'James', 'Madison', 'M', 'Software Developer', 1, 55000),
(2006, 'Michael', 'Greenback', 'M', 'Sales Assistant', 2, 85000),
(2007, 'Leslie', 'Peters', 'F', 'Sales Engineer', 2, 76000),
(2008, 'Max', 'Powers', 'M', 'Sales Representative', 2, 59000),
(2009, 'Stacy', 'Jacobs', 'F', 'Sales Manager', 2, 730000),
(2010, 'John', 'Henery', 'M', 'Sales Director', 2, 90000);
First of all your table and insertion of data indicating your table has Many:1 relation with department table(assuming department table exists). In this case "employee_id" will become primary key and "department_id" will be foreign key. The other way is you can create a composite primary key based on your requirement.
You can refer this for Foreign key creation
You made the department_id column to be your Primary Key, in which your department_id column has repeating values in different rows. Primary keys are unique values to identify rows in a table and cannot appear more than once. What you did is contrary to this PK requirement. Consider making a composite or surrogate key (eg. 1, 2, 3, ...n).
Not sure if this will help anyone at all reading this thread or if I'm the only one who has done this. I was getting the same error as you, and the reason was because I was trying to create a new record in the database table using UPDATE instead of INSERT INTO. I'm an amateur with SQL, so that was my bad.

Using data from 1 table to query another table

I have 2 tables. i want to use 'First_Name', and 'Middle_Name' from NAME table to get the 'Description' from DESCRIPTION table. Can i know how to construct this query in both SQL and LINQ expression! thanks alot!
CREATE TABLE NAME (
TICKET_ID int NOT NULL,
First_Name varchar(255),
Middle_Name varchar(255),
PRIMARY KEY (NAME )
);
INSERT INTO #NAME VALUES
(1, 'alex', 'black' ),
(2, 'john', 'hudson'),
(3, 'alice', 'channing')
CREATE TABLE description(
description_id int NOT NULL,
First_Name varchar(255),
Middle_Name varchar(255),
Description varchar(255),
PRIMARY KEY (description_id )
);
INSERT INTO #description
(1, 'alex', 'black' , 'tall'),
(2, 'john', 'hudson', 'strong'),
(3, 'alice', 'channing', 'short')
sql :
select d.Description from #description d
join #name n on d.First_name=n.first_name and d.last_name=n.last_name
Linq :
from d in description
join n in name on new on new { d.First_name, d.last_name } equals new { n.first_name, n.last_name }
select new { d.Description}
CREATE TABLE #NAME (
TICKET_ID int NOT NULL,
First_Name varchar(255),
Middle_Name varchar(255),
);
INSERT INTO #NAME VALUES
(1, 'alex', 'black' ),
(2, 'john', 'hudson'),
(3, 'alice', 'channing')
CREATE TABLE #description(
description_id int NOT NULL,
First_Name varchar(255),
Middle_Name varchar(255),
Description varchar(255),
PRIMARY KEY (description_id )
);
INSERT INTO #description values
(1, 'alex', 'black' , 'tall'),
(2, 'john', 'hudson', 'strong'),
(3, 'alice', 'channing', 'short')
select Description from #NAME A join
#description B on b.First_Name=a.First_Name
and b.Middle_Name=a.Middle_Name

How to generate a unique ID for every insert statement in SQL Server?

I want to give a unique ID for every insert statement I make, this is so I can see what rows was inserted together. I prefer that the unique "insert ID" start at 1 and increases by one like the IDENTITY(1,1) for rows.
Is there a easy way like IDENTITY to do that?
CREATE TABLE [dbo].[factTrade]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[insertedID] [int] NOT NULL,
[quantity] [int] NOT NULL,
[price] [decimal](20, 10) NOT NULL
)
INSERT INTO [dbo].[factTrade] ([insertedID], [quantity], [price])
VALUES (1, 6, 2.5), (1, 4, 3.7), (1, 3, 4.1), (1, 7, 8.5),
INSERT INTO [dbo].[factTrade] ([insertedID], [quantity], [price])
VALUES (2, 5, 5.2), (2, 1, 4.6)
This isn't the solution you asked for, but you could add a column with a default timestamp to find all rows inserted at the same time.
ALTER TABLE dbo.factTrade
ADD InsertDate DATETIME NOT NULL DEFAULT (GETDATE())
Guids are handy for things like that.
declare #insertid uniqueidentifier = newid();
CREATE TABLE [dbo].[factTrade](
[ID] [int] IDENTITY(1,1) NOT NULL,
[insertedID] [int] NOT NULL,
[quantity] [int] NOT NULL,
[price] [decimal](20, 10) NOT NULL,
[insertid] [uniqueidentifier] not null
)
INSERT INTO [dbo].[factTrade]
([insertedID]
,[quantity]
,[price]
,[insertid]
)
VALUES
(1, 6, 2.5,#insertid),
(1, 4, 3.7,#insertid),
(1, 3, 4.1,#insertid),
(1, 7, 8.5,#insertid)
set #insertid = newid(); --get another guid
INSERT INTO [dbo].[factTrade]
([insertedID]
,[quantity]
,[price]
,[insertid]
)
VALUES
(2, 5, 5.2,#insertid),
(2, 1, 4.6,#insertid)
If you need an integer value, then you can create another table:
CREATE TABLE inserts ([ID] INT IDENTITY(1,1)...)
Then from your app, insert a row into this, then use the generated identity value (SCOPE_IDENTITY()).
INSERT inserts DEFAULT VALUES;
SELECT #insertId = SCOPE_IDENTITY();
This is what I ended up doing, thank you for all the suggestions and comments.
DECLARE #insertedID INT
CREATE TABLE [dbo].[factTrade]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[insertedID] [int] NOT NULL,
[quantity] [int] NOT NULL,
[price] [decimal](20, 10) NOT NULL
)
CREATE SEQUENCE [dbo].[factTradeInsertedID] AS INT
START WITH 1
INCREMENT BY 1
SET #insertedID = NEXT VALUE FOR [dbo].[factTradeInsertedID] --1
INSERT INTO [dbo].[factTrade]
([insertedID]
,[quantity]
,[price])
VALUES
(#insertedID, 6, 2.5)
,(#insertedID, 4, 3.7)
,(#insertedID, 3, 4.1)
,(#insertedID, 7, 8.5)
SET #insertedID = NEXT VALUE FOR [dbo].[factTradeInsertedID] --2
INSERT INTO [dbo].[factTrade]
([insertedID]
,[quantity]
,[price])
VALUES
(#insertedID, 5, 5.2)
,(#insertedID, 1, 4.6)

How to output using recursive (parents -> children -> grandchildren)

CREATE TABLE PERSON
(
persID INT IDENTITY(1,1) PRIMARY KEY,
persFName VARCHAR(30) NOT NULL,
persLName VARCHAR(30) NOT NULL,
persDOB DATE,
motherID INT FOREIGN KEY REFERENCES person(persID),
fatherID INT FOREIGN KEY REFERENCES person(persID),
persDOD DATE,
persGender CHAR(1),
)
CREATE TABLE COUPLE
(
coupleID INT IDENTITY(1,1) PRIMARY KEY,
alphaSpouse INT NOT NULL FOREIGN KEY REFERENCES person(persID),
omegaSpouse INT NOT NULL FOREIGN KEY REFERENCES person(persID),
coupleStart DATE NOT NULL,
coupleEnd DATE,
)
INSERT INTO person (persFName, persLName, persDOB, motherID, fatherID, persDOD, persGender) VALUES
('Jim', 'Smith', '1920-05-15', NULL, NULL, '2001-04-21','M'),
('Agnes', 'Smith', '1922-09-21', NULL, NULL, '2003-06-01','F'),
('Linda', 'Howard', '1949-03-20', 2, 1, NULL,'F'),
('Helen', 'Bradley', '1942-11-28', 2, 1, NULL,'F'),
('Jim', 'Smith', '1953-02-10', 2, 1, NULL,'M'),
('Stephen', 'Smith', '1957-01-13', 2, 1, '2005-05-25','M'),
('Daniel', 'Smith', '1961-11-28', 2, 1, NULL,'M'),
('Michelle', 'Smith', '1963-07-02', NULL, NULL, NULL,'F'),
('Anne', 'Smith', '1958-04-22', NULL, NULL, NULL,'F'),
('Josh', 'Smith', '1990-01-28', 8, 7, NULL,'M'),
('Stephanie', 'Smith', '1992-05-18', 8, 7, NULL,'F'),
('Rachel', 'Smith', '1996-11-05', 8, 7, NULL,'F'),
('Reg', 'Howard', '1949-07-07', NULL, NULL, NULL,'M'),
('Richard', 'Howard', '1972-12-26', 3, 13, NULL,'M'),
('Phillip', 'Howard', '1975-06-01', 3, 13, NULL,'M'),
('Robert', 'Bradley', '1939-03-07', NULL, NULL, NULL,'M'),
('Matthew', 'Bradley', '1964-10-26', 4, 16, '2001-04-27','M'),
('Yvonne', 'Bradley', '1966-11-28', 4, 16, NULL,'F'),
('James', 'Bradley', '1971-01-26', 4, 16, NULL,'M'),
('Anna', 'Reuper', '1918-01-27', NULL, NULL, NULL,'F'),
('Ludwig', 'Reuper', '1923-07-01', NULL, NULL, '2001-07-01','M'),
('Heinz', 'Reuper', '1965-01-28', 20, 21, NULL,'M'),
('Veronica', 'Reuper', '1959-04-01', 20, 21, NULL,'F'),
('Marco', 'Johnson', '1958-09-04', NULL, NULL, NULL,'M'),
('Francesca', 'Reuper', '1990-11-01', 23, 24, NULL,'F'),
('Lou', 'Jung', '1940-02-03', NULL, NULL, NULL,'M'),
('Tammi', 'Sinclair', '1971-02-03', NULL, NULL, NULL,'F'),
('Lori', 'Navarro', '1973-12-15', NULL, NULL, NULL,'F'),
('Kattie', 'Paine', '1980-10-31', NULL, NULL, NULL,'F');
INSERT INTO couple (alphaSpouse,omegaSpouse, coupleStart, coupleEnd) VALUES
(1,2,'1940-05-22', NULL),
(3,13,'1969-07-30', '1973-10-01'),
(3,26,'1980-01-10', '1982-12-01'),
(4,16,'1963-04-05', NULL),
(6,9,'1979-06-21', NULL),
(7,8,'1987-09-14', NULL),
(20,21,'1936-10-26', NULL),
(23,24,'1988-05-01', '1997-07-01'),
(19,27,'1992-10-31', '1993-01-31'),
(19,28,'1995-08-18', '1997-04-27'),
(19,29,'2015-09-19', NULL);
I'm trying to list all the people who have grandchildren and how many grandchildren they each have. I'd like an ouput like this;
I attempted to do it below, but I got stuck trying to COUNT grandkids outside the WHERE subquery.. was I even on the right track?
SELECT grandp.persFName + ' ' + grandp.persLName, COUNT(grandkids.persID)
FROM person grandp
JOIN person child ON grandp.persID = child.motherID OR grandp.persID = child.fatherID
WHERE child.persID IN (SELECT grandkids.motherID
FROM person grandkids
union
SELECT grandkids.fatherID
FROM person grandkids)
GROUP BY grandp.persFName + ' ' + grandp.persLName
When you have hierarchical data like yours, it's best approached with common table expressions. This will allow you to build the hierarchical data into a form that you can later use - in your example, to count grandchildren. You can take advantage of building data by levels or distance from the root.
with temp (persid, ancestorid, level) as (
select persid, persid as ancestorid, 0 as level
from person
where motherid is null and fatherid is null
union all
select person.persid, temp.ancestorid, temp.level + 1 as level
from person
inner join temp on temp.persid = person.motherid or temp.persid = person.fatherid
)
select temp.ancestorid as persid,
person.persFName + ' ' + person.persLName as name,
count(*)
from temp
inner join person
on temp.ancestorid = person.persid
where level = 2
group by temp.ancestorid, person.persFName, person.persLName
The query builds a CTE of each person, it's ancestor and the level (0 = grandparents, 2 = grandchildren). You can then easily count grandchildren for each ancestor.
SQL Fiddle: http://sqlfiddle.com/#!3/99c97/2
(Note: I left the couple table out as it's not needed here).
Try this I just used common table expressions recursively to get the result
;WITH Allpersons AS
(
SELECT persID AS Id
,persFName+' '+persLName AS Name
,fatherID
,motherID
FROM PERSON
)
SELECT
GrandFatherCTE.Name
,COUNT(GrandFatherCTE.Id ) AS CountOfChild
FROM Allpersons AllPersonsCTE
INNER JOIN
Allpersons ParentsCte
ON
AllPersonsCTE.fatherID = ParentsCte.Id
OR
AllPersonsCTE.motherID = ParentsCte.Id
INNER JOIN
Allpersons GrandFatherCTE
ON
ParentsCte.fatherID = GrandFatherCTE.Id
OR
ParentsCte.motherID = GrandFatherCTE.Id
INNER JOIN
COUPLE
ON
GrandFatherCTE.Id = COUPLE.alphaSpouse
OR
GrandFatherCTE.Id = COUPLE.omegaSpouse
GROUP BY
GrandFatherCTE.Name
,COUPLE.coupleID
ORDER BY
CountOfChild ASC
,COUPLE.coupleID ASC

Resources