Trouble with creating a trigger to print a statement after insert - sql

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');

Related

Insert values in inheritance tables

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;

Add Column To one table on inserting value to another table

I have two tables Branch_TB and Branch_City.
Branch_TB :
CREATE TABLE Branch_TB(
Branch_Id int NULL,
Branch_Name varchar(50) NULL
)
Whenever there is an entry for Branch_Name, I want to add that entry as column name in Branch_City.
Is there any way for this. I don't know how to do this and haven't try any solution.
Thanks in advance.
You can achieve that using AFTER INSERT TRIGGER.
CREATE TABLE Branch_TB(
Branch_Id int NULL,
Branch_Name varchar(50) NULL
)
go
--drop table BranchCity
create table BranchCity(abc varchar(20))
go
create TRIGGER dbo.AddCol
ON Branch_TB
AFTER INSERT AS
BEGIN
DECLARE #NewVal VARCHAR(20)
DECLARE #AlterSQL VARCHAR(100)
CREATE TABLE #New
(
VAL VARCHAR(20)
)
INSERT INTO #New
select Branch_Name from inserted
select #NewVal = Val from #New
SET #AlterSQL = 'ALTER TABLE BranchCity add ' + #NewVal + ' VARCHAR(20)'
exec(#AlterSQL)
END
go
insert into Branch_Tb
values(1, 'City1')
go
insert into Branch_Tb
values(2, 'City2')
But in my opinion, you should re-evaluate your database design.
you need to create trigger on insert row in Branch_TB table.
In trigger you need to add code for Add column in require table.
How to create Trigger in Sql ? check this.
I understand it like you want to duplicate inserted value in some other table in column name. If this is true then you can try with OUTPUT:
INSERT INTO Branch_TB( Branch_Id, Branch_Name )
OUTPUT 'someValue1', Inserted.Branch_Name, 'someValue2'
INTO Branch_City ( someCol1, Name, comeCol2 )
VALUES ( 1, 'some name' )
you can try this
create proc proc_branch (#b_name varchar(50)
as
begin
exec('alter table Branch_city add column '+ #b_name + ';');
end
go
create trigger tr_branch
on branch_TB
for insert
as
begin
declare #branch_name varchar(50);
set #branch_name=(select branch_name from inserted)
exec proc proc_branch
end

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?

SQL Insert With Unique Constraint using Stored Procedure

This is a generic question with a specific example.
I have a table with three fields (genreID (PK IDENTITY), genre, and subGenre). The table has a unique constraint on (genre, subGenre) combination.
I am wondering how I could go about modifying the stored procedure to insert if it DOES NOT exist in the table, otherwise return the genreID of the existing genre if it DOES exist.
CREATE PROCEDURE spInsertGenre
#genreID int OUTPUT,
#genre varchar(100),
#subGenre varchar(100)= NULL
AS
BEGIN
INSERT INTO Genre
(
genre,
subGenre
)
Values (
#genre,
#subGenre
)
SELECT #genreID = SCOPE_IDENTITY()
END
GO
You can try to select the row that would be inserted by your SP before you do the insert:
CREATE PROCEDURE spInsertGenre
#genreID int OUTPUT,
#genre varchar(100),
#subGenre varchar(100)= NULL
AS
BEGIN
-- if the row to be inserted already exists, put the genreID into the #genreID output parameter
SELECT #genreID = genreID
FROM Genre
WHERE genre = #genre
AND subGenre = #subGenre
IF #genreID IS NULL -- if the genreID was not found, do an insert and select the new genreID to the #genreID output parameter
BEGIN
INSERT INTO Genre
(
genre,
subGenre
)
Values (
#genre,
#subGenre
)
SELECT #genreID = SCOPE_IDENTITY()
END
END
GO

How do I write a stored procedure that requires an id to be created and then used later in the same procedure?

I am trying to write a stored procedure that writes the details of a new user (NonMembers table) to a data base and then uses the auto generated id for that user in the next part of the code to register that user to a competition (registration table). My attempt at doing this is as follows but clearly my SQL skills are a long way from where they need to be?
All help would be greatly appreciated.
ALTER PROCEDURE [dbo].[RegisterNonMember]
#CompetitionId INTEGER,
#IsMember BIT,
#FirstName NVARCHAR(50),
#Surname NVARCHAR(50),
#Handicap INTEGER,
#Club NVARCHAR(50),
#CountyId INTEGER,
#CountryId INTEGER,
#PlayersStartTime TIME
AS
BEGIN
DECLARE #NonMember TABLE
(NonMemberId INTEGER,
FirstName NVARCHAR(50),
Surname NVARCHAR(50),
Handicap INTEGER,
Club NVARCHAR(50),
CountyId INTEGER,
CountryId INTEGER
)
INSERT INTO [dbo].[NonMembers]
(
FirstName
,Surname
,[Handicap]
,[Club]
,CountyId
,CountryId
)
VALUES
(#FirstName
,#Surname
,#Handicap
,#Club
,#CountyId
,#CountryId
)
--UPDATE #NonMember
--SET [#NonMember].NonMemberId = [dbo].[NonMembers].[NonMemberId]
--FROM [dbo].[NonMembers]
--JOIN #NonMember ON [#NonMember].NonMemberId = [dbo].[NonMembers].[NonMemberId]
--WHERE #NonMember.FirstName = [dbo].[NonMembers].[FirstName]
--AND #NonMember.Surname = [dbo].[NonMembers].[Surname]
--AND #NonMember.Handicap = [dbo].[NonMembers].[Handicap]
--AND #NonMember.Club = [dbo].[NonMembers].[Club]
DECLARE #Registration TABLE
(CompetitionId INTEGER,
IsMember BIT,
NonMemberId INTEGER,
PlayersStartTime TIME
)
INSERT INTO [dbo].[Registration]
(
[CompetitionId]
,[IsMember]
,[NonMemberId]
,[PlayersStartTime])
VALUES
(#CompetitionId
,#IsMember
,#NonMemberId
,#PlayersStartTime)
END
After your INSERT add:
DECLARE #UserID INT
SELECT #UserID = SCOPE_IDENTITY()