Insert values in inheritance tables - sql

CREATE TABLE projeto.Person (
Person_Code INT IDENTITY(1,1) NOT NULL,
birthDate DATE NOT NULL,
Name VARCHAR(50) NOT NULL,
PRIMARY KEY (Person_Code)
)
CREATE TABLE projeto.Student (
Student_Code INT REFERENCES projeto.Person (Person_Code),
payment INT NOT NULL,
PRIMARY KEY (Student_Code),
)
CREATE TABLE projeto.teacher (
payment INT NOT NULL,
teacher_Code INT,
PRIMARY KEY (teacher_Code),
CHECK (payment > 350)
)
How do I insert values ​​in student, paying attention that a student has all person attributes? e.g. student has name, birth_date etc.
I tried this:
INSERT INTO projeto.Person VALUES
('1961-03-26', John Adam')
but this only adds in a person, and I can't tell if its a student or not.

I guess its how to get the recently inserted Person_Code that you are asking? In which case use scope_identity().
declare #BirthDate date, #Name varchar(50), #Payment int, #IsStudent bit, #IsTeacher bit, #NewPersonCode int;
-- SET THE RELEVANT VARIABLE VALUES
-- Insert person
insert into projeto.Person (BirthDate, [Name])
select #BirthDate, #Name;
-- Get the Person_Code of the new person record
set #NewPersonCode = scope_identity();
-- Insert Student record if a student
insert into projeto.Student (Student_Code, Payment)
select #NewPersonCode, #Payment
where #IsStudent = 1;
-- Insert Teacher record if a teacher
insert into projeto.Teacher (Teacher_Code, Payment)
select #NewPersonCode, #Payment
where #IsTeacher = 1;

Related

Function not giving a response

I have created a database for an airline that currently has 3 tables: Table1: FLIGHTS, Table2: Clients, Table3: Reservation, and I want to create a function that returns the time left in the month from the reservation made till the flights date inside a function. After I run it, nothing is returning. Any tips?
DROP DATABASE if exists Chartered_Airlines;
CREATE DATABASE Chartered_Airlines;
USE Chartered_Airlines;
CREATE TABLE FLIGHTS(FLIGHT_NO INT(5) NOT NULL, DEPARTURE VARCHAR(15), ARRIVAL VARCHAR(15), TYPEFL VARCHAR(15), SEATS INT(4) NOT NULL, FREE_SEATS INT(4), FLIGHT_DATE DATE,
PRIMARY KEY(FLIGHT_NO));
CREATE TABLE CUSTOMERS(CL_NO INT(5) NOT NULL, LAST_NAME VARCHAR(15) NOT NULL, FIRST_NAME VARCHAR(15) NOT NULL, CITIZENSHIP VARCHAR(15) NOT NULL, B_DATE DATE,
PRIMARY KEY(CL_NO));
CREATE TABLE RESERVATIONS(RES_NO INT(5) NOT NULL, CL_NO INT(5) NOT NULL, FLIGHT_NO INT(5), COST FLOAT(15), RES_DATE DATE,
PRIMARY KEY(RES_NO),
FOREIGN KEY(FLIGHT_NO) REFERENCES FLIGHTS(FLIGHT_NO),
FOREIGN KEY(CL_NO) REFERENCES CUSTOMERS(CL_NO));
SHOW TABLES;
INSERT INTO FLIGHTS VALUES(10,'ATHENS','LONDON','EXTERNAL',310,34, '2023/10/04');
INSERT INTO FLIGHTS VALUES(20,'ATHENS','MYKONOS','INTERNAL',100,5, '2022/12/12');
INSERT INTO FLIGHTS VALUES(30,'ATHENS','PARIS','EXTERNAL',256,16, '2022/09/07');
INSERT INTO CUSTOMERS VALUES(5472,'ALEKSANDRAKIS','GEORGIOS','GREECE','1989/01/01');
INSERT INTO CUSTOMERS VALUES(1354,'STAVROU','ANTREAS','GREECE','1977/07/07');
INSERT INTO CUSTOMERS VALUES(6598,'AMALFIO','ROBERTO','ITALY','1995/05/02');
INSERT INTO CUSTOMERS VALUES(1953,'EUSTATHIOU','NIKOS','GREECE','2001/06/03');
INSERT INTO CUSTOMERS VALUES(1387,'STAKAS','VASILLIS','GREECE','1990/01/07');
INSERT INTO RESERVATIONS VALUES(3174,5472,10,6482, '2020/03/02');
INSERT INTO RESERVATIONS VALUES(3143,1354,10,6482, '2021/05/09');
INSERT INTO RESERVATIONS VALUES(1286,6598,20,662, '2022/10/12');
INSERT INTO RESERVATIONS VALUES(3275,1953,20,662, '2022/09/08');
INSERT INTO RESERVATIONS VALUES(7654,1387,30,264, '2022/09/06');
SELECT * FROM FLIGHTS;
SELECT * FROM CUSTOMERS;
SELECT * FROM RESERVATIONS;
DESC FLIGHTS;
DESC RESERVATIONS;
DESC CUSTOMERS;
DELIMITER //
CREATE FUNCTION TIME_LEFT(RES_NO INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE TIME_LEFT INT DEFAULT 0;
SELECT TIMESTAMPDIFF(MONTH,RESERVATIONS.RES_DATE,FLIGHTS.FLIGHT_DATE) INTO TIME_LEFT FROM RESERVATIONS
WHERE RES_NO = RES_NO AND RESERVATIONS.FLIGHT_NO = FLIGHTS.FLIGHT_NO ;
RETURN TIME_LEFT;
END;
//
SELECT TIME_LEFT(3143);
I was expecting that it returns the date difference between reservation made date and flight date
Your forgot to use join and also use a variable name for holding the value passed in function:
DELIMITER //
CREATE FUNCTION TIME_LEFT(VAR_RES_NO INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE TIME_LEFT INT DEFAULT 0;
SELECT TIMESTAMPDIFF(MONTH,RESERVATIONS.RES_DATE,FLIGHTS.FLIGHT_DATE) INTO TIME_LEFT FROM RESERVATIONS join FLIGHTS
WHERE RES_NO = VAR_RES_NO AND RESERVATIONS.FLIGHT_NO = FLIGHTS.FLIGHT_NO ;
RETURN TIME_LEFT;
END;
//
I think you need to include the table Flights in the SELECT statement, as well as specify the difference between RES_NO in the input vs reservations e.g.,
CREATE FUNCTION TIME_LEFT(RES_NO_in INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE TIME_LEFT INT DEFAULT 0;
SELECT TIMESTAMPDIFF(MONTH,RESERVATIONS.RES_DATE,FLIGHTS.FLIGHT_DATE) INTO TIME_LEFT
FROM RESERVATIONS, FLIGHTS
WHERE RESERVATIONS.RES_NO = RES_NO_in AND RESERVATIONS.FLIGHT_NO = FLIGHTS.FLIGHT_NO;
RETURN TIME_LEFT;
END;
or
CREATE FUNCTION TIME_LEFT(RES_NO_in INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE TIME_LEFT INT DEFAULT 0;
SELECT TIMESTAMPDIFF(MONTH,RESERVATIONS.RES_DATE,FLIGHTS.FLIGHT_DATE) INTO TIME_LEFT
FROM RESERVATIONS
INNER JOIN FLIGHTS ON RESERVATIONS.FLIGHT_NO = FLIGHTS.FLIGHT_NO
WHERE RESERVATIONS.RES_NO = RES_NO_in;
RETURN TIME_LEFT;
END;

Trouble with creating a trigger to print a statement after insert

I am working on a project where I need to create a trigger that prints a statement each time an insert is performed on a table called enrolled.
This trigger is expected to print the faculty name, meeting location, time, student name after an insert is performed but when I run this trigger, it completes but after an insert is performed on the enrolled table, it does not print any information but the insert does complete and populates the table with the values. this is the test code I created below, along with the tables required to pull each value and a sample insert statement. any help is greatly appreciated.
USE test
GO
CREATE TRIGGER afterinsertprint on test.dbo.enrolled
AFTER INSERT
AS
BEGIN
DECLARE #studentname VARCHAR(30), #meetat varchar(30), #facultyname VARCHAR (30), #location NVARCHAR(10), #studentnumber int, #coursename NVARCHAR(12)
SELECT #studentnumber = snum, #coursename = cname FROM INSERTED;
SET #studentname = (SELECT sname from test.dbo.student WHERE snum = #studentnumber)
SELECT #facultyname = FNAME from test.dbo.faculty f join test.dbo.student s ON s.DEPT_ID = f.DEPT_ID where s.snum in
(SELECT snum FROM test.dbo.enrolled WHERE snum = #studentnumber and CNAME = #coursename);
SELECT #meetat = meets_at, #location = room FROM test.dbo.class WHERE cname IN (SELECT cname FROM test.dbo.enrolled
WHERE snum = #studentnumber and cname = #coursename);
IF (#studentnumber IS NOT NULL and #coursename IS NOT NULL)
BEGIN
PRINT (#studentname + #facultyname + #meetat + #location)
END;
END;
Below are the DML/DLL for table creation/insert
CREATE TABLE dbo.STUDENT
(snum int,
sname nvarchar(12),
MAJOR nvarchar(12),
DEPT_ID int,
slevel nvarchar(12),
AGE int,
CONSTRAINT STUDENT_SNUM_pk PRIMARY KEY (SNUM));
--
CREATE TABLE dbo.CLASS
(CNAME nvarchar(12),
MEETS_AT time,
ROOM nvarchar(10),
FID int,
CONSTRAINT CLASS_CNAME_pk PRIMARY KEY (CNAME));
--
CREATE TABLE dbo.ENROLLED
(SNUM int,
CNAME nvarchar(12));
--
CREATE TABLE dbo.FACULTY
(FID int,
FNAME nvarchar(40),
DEPT_ID int,
CONSTRAINT FACULTY_FID_pk PRIMARY KEY (FID));
--
CREATE TABLE dbo.DEPARTMENT
(DEPTid int,
DNAME nvarchar(100),
LOCATION nvarchar(100),
CONSTRAINT DEPARTMENT_DEPTID_pk PRIMARY KEY (DEPTID));
insert into dbo.STUDENT values (1234,'T.Banks','ME',3,'SR',19);
insert into dbo.DEPARTMENT values (1,'Computer Sciences','West Lafayette');
insert into dbo.FACULTY values (107,'Y.Walton',1);
insert into dbo.CLASS values ('ENG400',cast('08:30' as time),'U003',107);
insert into dbo.ENROLLED values (1234,'ENG400');

SQL-SERVER Procedure How do i insert row one table then insert row into another table link to another table as foreign key

database diagram
For sql-server
How can I insert a SKU row into table SKU_DATA, then insert the SKU into INVENTORY table with all branches and Quantity on hand=2 and Quantityonhand=0.
I need to insert a SKU item into SKUDATA and correspond row in inventory table for all existing branches Quantityonhand=2 and Quantityonhand = 0.
Please help Thanks
BRANCH
name varchar (30) not NULL,
managerNum INT NOT NULL,
SKU_DATA
SKU Int NOT NULL IDENTITY (1000,1),
description varchar (40) NOT NULL UNIQUE,
department varchar(30) NOT NULL default 'Home Entertainment',
sellingPrice numeric (7,2) NOT NULL ,
INVENTORY
SKU Int NOT NULL,
branch varchar (30) NOT NULL ,
quantityOnHand Int NOT NUll ,
quantityOnOrder Int NOT NUll ,
Procedure:
Create procedure InsertNewSkuWithInventory
#description varchar (40),
#department varchar(30),
#sellingPrice numeric (7,2),
AS
Declare #rowcount as int
Declare #SKU as int
Declare #branch as varchar(30)
Select #rowcount = COUNT(*)
from dbo.SKU_DATA
Where description = #description
And department = #department
And sellingPrice = #sellingPrice;
BEGIN
INSERT INTO dbo.SKU_DATA (description, department, sellingPrice)
VALUES (#description, #department, #sellingPrice);
Select #SKU =SKU
From dbo.SKU_DATA
Where description = #description
And department = #department
And sellingPrice = #sellingPrice;
DECLARE SKUCursor CURSOR FOR
SET #branch = ##IDENTITY
Select SKU
From dbo.inventory
Where
CLOSE SKUCursor
DEALLOCATE SKUCursor
END
There are two problems here: first, how to get the generated IDENTITY value for the newly inserted row into SKU_DATA table, and second, how to one row into INVENTORY table for each branch.
If you're inserting only a single row into SKU_DATA, then use the scope_identity() function (never use the ##IDENTITY!). Like this:
INSERT INTO dbo.SKU_DATA (description, department, sellingPrice)
VALUES (#description, #department, #sellingPrice);
set #SKU = scope_identity()
Then you do insert into INVENTORY by selecting from BRANCH table:
insert dbo.INVENTORY (SKU, branch, quantityOnHand, quantityOnOrder)
select #SKU, b.name, 2, 0
from dbo.Branch b
Hope you can work the complete solution out from this.

TSQL Updating record ID after insert

I have a stored procedure that takes data from a table and creates a record in another table in the following structure:
TableA = Source Data
TableB = Destination 1
First, we query all the data we need from the source table and insert it into TableB. This table has an identity called recordID.
This is done through an INSERT from a Select statement which could contain a variable amount of records.
When this is complete, I need to update a column in TableA called TableBRef with the recordID that was created from the insert in TableB.
I tried using Scope_Identity() but because its inserting multiple records, it only gets the ID of the last record.
I also tried to create a SQLFiddle but it appears the site is having issues as I am getting the error Unknown Error Occurred: XML document structures must start and end within the same entity.: on even the sample fiddle.
Any recommendations to be able to accomplish what I am needing?
Update:
Here is some example code since SQLFiddle is down:
-- This is our source data
DECLARE #source TABLE (recordID INT IDENTITY (1,1), name VARCHAR(100), phone VARCHAR(20));
INSERT INTO #source(name , phone)
VALUES (
'Bob Desk', '123-456-7899',
'Don Mouse', '123-456-5555',
'Mike Keyboard', '123-456-7899',
'Billy Power', '122-222-1134'
)
-- This is the first step in the process - Inserting the records into our table
DECLARE #data1 TABLE (recordID INT IDENTITY (1,1), name VARCHAR(100) NOT NULL, phone VARCHAR(20) NOT NULL, sourceID INT NULL)
SELECT name, phone
FROM #source;
-- Based on some condition, we take records from #data1 and insert them into #data2
DECLARE #data2 TABLE (recordID INT IDENTITY (1,1), name VARCHAR(100) NOT NULL, phone VARCHAR(20) NOT null)
INSERT INTO #data2( name, phone)
SELECT name, phone
FROM #data1
WHERE phone <> '123-456-5555'
-- I now need to update #data1 with the recordID that was created from inserting the data into #data2
UPDATE #data1 SET SOURCEID = 'blah'
Lets setup some tables:
DECLARE #source TABLE
(
recordID INT IDENTITY (1,1),
name VARCHAR(100),
phone VARCHAR(20),
sourceID INT
);
This will store all of the updates coming out of the insert statement:
DECLARE #NewRecord TABLE
(
recordID INT,
name VARCHAR(100),
phone VARCHAR(20)
);
Now we insert the records, and we output the updated record into a table variable to get the new id's:
INSERT INTO #source (name, phone)
OUTPUT inserted.recordid, inserted.name, inserted.phone INTO #NewRecord
VALUES
('Bob Desk', '123-456-7899'),
('Don Mouse', '123-456-5555'),
('Mike Keyboard', '123-456-7899'),
('Billy Power', '122-222-1134')
Here is the output:
SELECT * FROM #NewRecord
recordID name phone
1 Bob Desk 123-456-7899
2 Don Mouse 123-456-5555
3 Mike Keyboard 123-456-7899
4 Billy Power 122-222-1134
Becuase when we are inserting data into data2 with new identity column so we lost source record id so I used name and phone to find what I had inserted --this might not work properly if there are duplicate name and phone seems like there is some design flaw.
but here is some thing you can try this below
-- This is our source data
DECLARE #source TABLE (recordID INT IDENTITY (1,1), name VARCHAR(100), phone VARCHAR(20));
INSERT INTO #source(name , phone)
VALUES (
'Bob Desk', '123-456-7899'),
('Don Mouse', '123-456-5555'),
('Mike Keyboard', '123-456-7899'),
('Billy Power', '122-222-1134')
-- This is the first step in the process - Inserting the records into our table
DECLARE #data1 TABLE (recordID INT IDENTITY (1,1), name VARCHAR(100) NOT NULL, phone VARCHAR(20) NOT NULL, sourceID INT NULL)
--Capture inserts using another table
DECLARE #cdcapture1 TABLE (recordID INT , name VARCHAR(100) NOT NULL, phone VARCHAR(20) NOT null)
INSERT INTO #data1(name,phone)
OUTPUT Inserted.recordID,Inserted.name,Inserted.phone INTO #cdcapture1
SELECT name, phone
FROM #source;
--Capture inserts using another table
DECLARE #cdcapture2 TABLE (recordID INT , name VARCHAR(100) NOT NULL, phone VARCHAR(20) NOT null)
-- Based on some condition, we take records from #data1 and insert them into #data2
DECLARE #data2 TABLE (recordID INT IDENTITY(1,1), name VARCHAR(100) NOT NULL, phone VARCHAR(20) NOT null)
INSERT INTO #data2( name, phone)
OUTPUT Inserted.* INTO #cdcapture2
SELECT name, phone
FROM #cdcapture1 c1
--WHERE phone <> '123-456-5555'
-- Becuase when we are inserting data into data2 with new identity column so we lost source record id
UPDATE d1
SET d1.sourceid = c2.recordid
FROM #data1 d1 INNER JOIN #cdcapture1 c1 ON d1.recordID = c1.recordID
INNER JOIN #cdcapture2 c2 ON c2.NAME = c1.NAME AND c2.phone = c1.phone
SELECT * FROM #data1
-- This is our source data
DECLARE #source TABLE
(
recordID INT IDENTITY (1,1),
name VARCHAR(100),
phone VARCHAR(20)
);
INSERT INTO #source(name , phone)
VALUES
('Bob Desk', '123-456-7899'),
('Don Mouse', '123-456-5555'),
('Mike Keyboard', '123-456-7899'),
('Billy Power', '122-222-1134');
-- This is the first step in the process - Inserting the records into our table
DECLARE #data1 TABLE
(
recordID INT IDENTITY (1,1),
name VARCHAR(100) NOT NULL,
phone VARCHAR(20) NOT NULL,
sourceID INT NULL
)
INSERT INTO #data1 (name, phone )
SELECT name, phone
FROM #source;
-- Based on some condition, we take records from #data1 and insert them into #data2
DECLARE #data2 TABLE
(
recordID INT IDENTITY (1,1),
name VARCHAR(100) NOT NULL,
phone VARCHAR(20) NOT null,
data1recid INT
)
INSERT INTO #data2( name, phone, data1recid)
SELECT name, phone, recordID
FROM #data1
WHERE phone <> '123-456-5555'
-- I now need to update #data1 with the recordID that was created from inserting the data into #data2
UPDATE m
set m.sourceID = d.recordID
FROM #data1 m
INNER JOIN #data2 d
ON m.recordID = d.data1recid
Here is the output:
SELECT * FROM #data1
recordID name phone sourceID
1 Bob Desk 123-456-7899 1
2 Don Mouse 123-456-5555 NULL
3 Mike Keyboard 123-456-7899 2
4 Billy Power 122-222-1134 3
Is this more along the lines of what you needed?

User Defined Scalar functions in SQL

I am new to SQL and am learning User Defined Functions in SQL
I have two tables and I have given the rows I have inserted to those tables.
--Table1
create table sql_exam(
exa_examid bigint not null primary key,
exa_name varchar(100) not null,
exa_maxmark decimal(5,2) not null,
exa_minmarkreqdforpass decimal(5,2) not null,
exa_examscheduletime datetime not null
)
--Rows inserted into Table1
insert into sql_exam(exa_examid,exa_name,exa_maxmark,exa_minmarkreqdforpass,exa_examscheduletime) values (1,'Maths',100,40,'2012-10-10 10:00')
insert into sql_exam(exa_examid,exa_name,exa_maxmark,exa_minmarkreqdforpass,exa_examscheduletime) values (2,'English',75,35,'2012-10-11 10:00')
--Table2
create table sql_studentmarks(
stm_studentid int not null primary key,
stm_examid bigint foreign key references sql_exam(exa_examid),
stm_mark decimal(5,2)
)
--Rows inserted into Table2
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (1,1,80)
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (2,1,90)
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (3,1,40)
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (1,2,70)
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (2,2,60)
insert into sql_studentmarks(stm_studentid,stm_examid,stm_mark) values (3,2,17)
I require a help about creating Scalar functions and I need to get
A scalar function which will return the Student ID of the student who got highest mark in 'Maths'
A tabular function which will return the student ID and marks gained by the student who got highest total mark.
Am just trying to learn SQL. I have tried - "
create function fnGetMathsHightest()
returns int
as
begin
declare #st_id int
return #st_id
end
select dbo.fnGetMathsHightest()
from sql_studentmarks
where stm_examid=1
group by stm_studentid
having stm_mark=max(stm_mark)
for the first one. It does not look good.
It looks like this what you want for 1.
CREATE FUNCTION ssfnGetStudenytId
(
-- Add the parameters for the function here
)
RETURNS int
AS
BEGIN
declare #vId as int
set #vId = Select stm_studentid from sql_studentmarks where stm_mark = (SELECT MAX( stm_mark )from sql_studentmarks )
RETURN #vId
END