How to insert data into another table when the condition is met with trigger - sql

I have these 4 tables:
CREATE TABLE dbo.person
(
personId INT IDENTITY(1,1) NOT NULL,
firstName NVARCHAR(30) NOT NULL,
lastName NVARCHAR(30) NOT NULL,
CONSTRAINT pkPerson PRIMARY KEY (personId),
);
CREATE TABLE dbo.personRegistration
(
person_registrationId INT IDENTITY(1,1) NOT NULL,
personId INT,
firstName NVARCHAR(30) NOT NULL,
lastName NVARCHAR(30) NOT NULL,
confirmed NCHAR(1) DEFAULT 'N' NOT NULL,
CONSTRAINT pkpersonRegistration PRIMARY KEY (person_registrationId),
CONSTRAINT fkpersonRegistration FOREIGN KEY (personId) REFERENCES dbo.person (personId)
CONSTRAINT personConfirmed CHECK (confirmed IN ('Y', 'N'))
);
CREATE TABLE dbo.person_organizationalUnit
(
personId INT NOT NULL,
organizationalUnitId INT NOT NULL,
CONSTRAINT pkorganizationalUnit PRIMARY KEY (personId, organizationalUnitId),
CONSTRAINT fkperson FOREIGN KEY (personId) REFERENCES dbo.person (personId),
CONSTRAINT fkorganizationalUnit FOREIGN KEY (organizationalUnitId) REFERENCES dbo.organizatinalUnit(unicOrgUnitId),
);
CREATE TABLE dbo.organizatinalUnit
(
organizationalUnitId INT IDENTITY(1,1) NOT NULL,
organizationalUnitName NVARCHAR(130) NOT NULL,
CONSTRAINT pkorganizationalUnit PRIMARY KEY (organizationalUnitId)
);
I need to create a trigger which will do that when I add new person in table personRegistration (his personId is set to NULL, and initial value for confirmed is 'N') and when I update personRegistration and set confirmed to 'Y', that person is going to be inserted into table person (value for personId is generated because the personId is an identity column) and the confirmed is going to change it's value to 'Y' and is going to be inserted in table person_organizationalUnit. I have written the trigger but the problem is when I update the personRegistration for more than one person my data double with each update.
CREATE TRIGGER personConfirmed
ON dbo.personRegistration
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.person (firstName, lastName)
SELECT
firstName, lastName
FROM
dbo.personRegistration
SET NOCOUNT ON
DECLARE #idPerson int
SELECT #idPerson = personId
FROM dbo.person
INSERT INTO dbo.person_organizationalUnit (personId, organizationalUnitId)
SELECT #idPerson, I.organizationalUnitId
FROM Inserted AS I
JOIN dbo.person p ON p.personId = #idPerson
WHERE confirmed = 'Y';
END
Data for insert:
INSERT INTO dbo.personRegistration (personId, firstName, lastName, confirmed)
VALUES (NULL, 'John', 'Smith', 'N');
Data for update:
UPDATE dbo.personRegistration
SET confirmed = 'Y'
WHERE personRegistrationId = 1;

SQL Server triggers works with sets not single register i did some small changes in your trigger
create TRIGGER dbo.usp_PersonConfirmed ON dbo.personRegistration
AFTER UPDATE
AS
BEGIN
-- create person if not exists
INSERT INTO dbo.person (firstName, lastName)
SELECT firstName, lastName
FROM dbo.personRegistration p
where not exists(select * from dbo.Person where firstName = p.firstName
and lastName = p.lastName)
-- create orgonization unit if person dont exist and confirmed is Y
INSERT INTO dbo.person_organizationalUnit (personId, organizationalUnitId)
SELECT i.personId, I.organizationalUnitId
FROM Inserted AS I
where not exists(select * from dbo.person_organizationalUnit where
personId = i.personId)
and confirmed = 'Y';
-- update orgonization unit if person exist and confirmed is Y
update pou set organizationalUnitId = I.organizationalUnitId
from dbo.person_organizationalUnit pou
inner join Inserted AS I on i.personID = pou.personId
where i.confirmed = 'Y';
END

Your trigger has a fatal flaw: it does not deeal properly with multiple rows. It is also not using the inserted table in the first INSERT, and instead selecting from the whole original table.
So you need to OUTPUT the identity column from the first insert in order to use it in the second.
Because you don't have the identity column yet, you need to join onto firstName and lastName, which I need not say isn't a very good primary key
CREATE OR ALTER TRIGGER personConfirmed
ON dbo.personRegistration
AFTER UPDATE
AS
SET NOCOUNT ON
IF NOT UPDATE(confirmed) OR NOT EXISTS (SELECT 1 FROM inserted)
RETURN; --early bailout
DECLARE #ids TABLE (personId int PRIMARY KEY, firstName nvarchar(100), lastName nvarchar(100));
INSERT INTO dbo.person (firstName, lastName)
OUTPUT inserted.personId, inserted.firstName, inserted.lastName
SELECT
i.firstName,
i.lastName
FROM
inserted i
WHERE i.confirmed = 'Y';
INSERT INTO dbo.person_organizationalUnit (personId, organizationalUnitId)
SELECT ids.personId, i.organizationalUnitId
FROM inserted AS i
JOIN #ids ids ON i.firstName = ids.firstName AND i.lastName = ids.lastName;
Ideally, you have some kind of unique primary key on personRegistration. then your trigger would look like this:
CREATE OR ALTER TRIGGER personConfirmed
ON dbo.personRegistration
AFTER UPDATE
AS
SET NOCOUNT ON
IF NOT UPDATE(confirmed) OR NOT EXISTS (SELECT 1 FROM inserted)
RETURN; --early bailout
DECLARE #ids TABLE (personId int PRIMARY KEY, registrationId int);
MERGE dbo.person p
USING (
SELECT *
FROM inserted i
WHERE i.confirmed = 'Y'
) i
ON 1 = 0 -- never match
WHEN NOT MATCHED THEN
INSERT (firstName, lastName)
VALUES (i.firstName, i.lastName)
OUTPUT inserted.personId, i.organizationalUnitId
INTO #ids (personId, organizationalUnitId)
;
INSERT INTO dbo.person_organizationalUnit (personId, organizationalUnitId)
SELECT ids.personId, i.organizationalUnitId
FROM #ids ids;
We need that funny MERGE because we want to OUTPUT columns that we are not inserting. You can only do this using MERGE.

Related

If exists update the XML column or insert into new row in reference table

If exists data into parent table then update the child table on XML column based on the reference id, other wise insert into row.
CREATE TABLE Person
(
PersonId INT CONSTRAINT PK_Person_PersonId PRIMARY KEY,
Name VARCHAR(50),
SubMittedDate DATETIME,
SubmittedBy INT,
RejectedDate DATETIME,
RejectedBy INT
)
INSERT INTO Person VALUES(1, 'Sai', GETDATE(),1,null,null)
CREATE TABLE PersonXML
(
PersonXMLId INT IDENTITY(1,1) CONSTRAINT PK_PersonXML_PersonId PRIMARY KEY,
PersonId INT CONSTRAINT FK_PersonXML_Person FOREIGN KEY REFERENCES Person(PersonId),
Name VARCHAR(50),
PersonHistory XML
)
INSERT INTO PersonXML(PersonId,Name,PersonHistory )
SELECT PersonId
,Name
,(SELECT PersonId
,Name
,SubMittedDate
,SubmittedBy
,ISNULL(RejectedDate,0) AS RejectedDate
,ISNULL(RejectedBy, 0) AS RejectedBy
FROM Person FOR XML PATH('PersonHistory') )
FROM Person
SELECT * FROM Person
SELECT * FROM PersonXML
Whenever i Update Person Table in RejectedDate, RejectedBy Column then those changes has to reflect in PersonXML table on PersonHistory column automatically could anyone please find me way to achieve it.
UPDATE Person SET RejectedDate = GETDATE(), RejectedBy= 100 WHERE PersonId = 1
DECLARE #PersonId int,#RejectedDate datetime,#RejectedBy int
SET #PersonId=1
SET #RejectedDate=Getdate()+1
SET #RejectedBy=105
CREATE TABLE Person
(
PersonId INT CONSTRAINT PK_Person_PersonId PRIMARY KEY,
Name VARCHAR(50),
SubMittedDate DATETIME,
SubmittedBy INT,
RejectedDate DATETIME,
RejectedBy INT
)
INSERT INTO Person VALUES(1, 'Sai', GETDATE(),1,null,null)
CREATE TABLE PersonXML
(
PersonXMLId INT IDENTITY(1,1) CONSTRAINT PK_PersonXML_PersonId PRIMARY KEY,
PersonId INT CONSTRAINT FK_PersonXML_Person FOREIGN KEY REFERENCES Person(PersonId),
Name VARCHAR(50),
PersonHistory XML
)
INSERT INTO PersonXML(PersonId,Name,PersonHistory )
SELECT PersonId
,Name
,(SELECT PersonId
,Name
,SubMittedDate
,SubmittedBy
,ISNULL(RejectedDate,0) AS RejectedDate
,ISNULL(RejectedBy, 0) AS RejectedBy
FROM Person FOR XML PATH('PersonHistory') )
FROM Person
IF Exists(SELECT * FROM Person WHERE PersonId=#PersonId)
BEGIN
UPDATE Person
SET
RejectedDate =#RejectedDate ,RejectedBy=#RejectedBy
WHERE PersonId=#PersonId
UPDATE PersonXML
SET PersonHistory=
(SELECT PersonId
,Name
,SubMittedDate
,SubmittedBy
,ISNULL(RejectedDate,#RejectedDate) AS RejectedDate
,ISNULL(RejectedBy,#RejectedBy) AS RejectedBy
FROM Person FOR XML PATH('PersonHistory') )WHERE PersonId=#PersonId
END
ELSE
BEGIN
INSERT INTO Person
Select #PersonId,'', GETDATE(),1,#RejectedDate,#RejectedBy
END
SELECT * FROM Person
SELECT * FROM PersonXML

How to trigger a table to change the value of another table column

I've created three tables.
CREATE TABLE Clients
(
ClientID INT IDENTITY(1,1) PRIMARY KEY,
First_Name VARCHAR(50) NOT NULL,
Last_Name VARCHAR(50) NOT NULL,
)
CREATE TABLE Reservation
(
ReservationID INT IDENTITY(1,1) PRIMARY KEY,
ClientID INT FOREIGN KEY (ClientID) REFERENCES Clients(ClientID),
Reservation_paid VARCHAR(3) DEFAULT 'NO',
)
CREATE TABLE Payment
(
Payment_ID INT IDENTITY(1,1) PRIMARY KEY,
ClientID INT FOREIGN KEY (ClientID) REFERENCES Clients(ClientID),
ReservationID INT FOREIGN KEY (ReservationID) REFERENCES Reservation(ReservationID),
)
I would like to change the value of the column Reservation_paid to YES at the Reservation table whenever the Client does pay the reservation, and i want to do it automatically with trigger.
Example: If the ClientID at the Reservation table exists at the Payment table automatically the value of the Reservation_paid will set to YES.
Thank you in advance.
CREATE TRIGGER trgAfterInsert ON [dbo].[Payment]
FOR INSERT
AS
declare #ClientID int;
select #ClientID =i.ClientID from inserted i;
if update(ClientID)
UPDATE Reservation set Reservation_paid='Yes' WHERE
ClientID=#ClientID;
--PRINT 'AFTER INSERT trigger fired.'
After Insert Trigger should do something like this
UPDATE R
SET Reservation_paid = 'Yes'
FROM reservation R
WHERE EXISTS (SELECT 1
FROM INSERTED I
WHERE I.clientid = R.clientid
AND I.reservationid = R.reservationid)
CREATE TRIGGER trgAfterInsert ON [dbo].[Payment]
FOR INSERT
AS
declare #ClientID int;
select #ClientID =i.ClientID from inserted i;
insert into Reservation(ClientID,Reservation_paid)
values(#ClientID,'Yes');
--PRINT 'AFTER INSERT trigger fired.'
GO
Write a trigger that will work on table Reservation after any insert or update on ClientId column of table Payment. Then match the ClientID with ClientID column of Reservation table and update the corresponding Reservation_paid to YES.
Edit:
The trigger will be like this
CREATE TRIGGER `UpdateReservation_paid` AFTER INSERT OR UPDATE ON `Payment`
FOR EACH ROW BEGIN
AS
begin
update Reservation
SET Reservation_paid='YES'
Where NEW.ClientID = Reservation.ClientID
and NEW.ReservationID = Reservation.ReservationID
end

How to group several INSERTs?

I'm inserting data from one table into several others. The first insert will create a new userid. This new userid will be used in succeeding inserts. I will also continue inserting username from the source table into other tables. The chain of inserts below are for one user. There will be probably 2000 users involved.
I'm familiar with how this can be done using a cursor. Is there some other way to do this chain of inserts without a cursor?
insert into table 1 using #username and #firstname from source table
insert into table 2 using userid generated from table 1 (userid1)
insert into table 3 using #username and userid1
insert into table 4 using userid1
You can use the Output Clause of an Insert statement to capture generated Ids in bulk.
For example:
Create Table dbo.Source (
FirstName nvarchar(100),
LastName nvarchar(100)
);
Create Table dbo.Attrs (
Id int Identity Not Null Primary Key,
Name nvarchar(100) Not Null,
DefaultVal nvarchar(100)
);
Create Table dbo.Table1 (
Id Int Identity Not Null Primary Key,
FirstName nvarchar(100),
LastName nvarchar(100)
);
Create Table dbo.Table2 (
Id int Identity Not Null Primary Key,
Table1ID int Not Null Foreign Key References dbo.Table1 (Id),
AttrId int Not Null Foreign Key References dbo.Attrs (Id)
);
Insert Into dbo.Source Values
(N'Mickey', N'Mouse'),
(N'Donald', N'Duck'),
(N'Goofy', Null);
Insert Into dbo.Attrs Values
('Size', 'Small'),
('Wings', 'No');
Declare #Temp1 Table (Id Int, FirstName nvarchar(100), LastName nvarchar(100))
Declare #Temp2 Table (Id int, Table1ID int, AttrId int)
Insert Into dbo.Table1
(FirstName, LastName)
Output
inserted.Id, inserted.FirstName, inserted.LastName
Into
#Temp1
Select
FirstName, LastName
From
dbo.Source
Insert Into dbo.Table2
(Table1ID, AttrId)
Output
inserted.Id, Inserted.Table1ID, Inserted.AttrID
Into
#Temp2
Select
t.Id,
a.Id
From
#Temp1 t
Cross Join
dbo.Attrs a
Select * From #Temp2
http://sqlfiddle.com/#!3/31110/3

Foreign Key Not Populating with Primary Key Values

I have searched for an answer but am not finding it. I have 2 tables. Both have an auto-generated PK. The PK from table 2 is an FK in table 1. Since they are both auto-generated I assumed the FK in table 1 would populate with the value that is auto-generated from table 2 but it is not working. The FK in table 1 ends up null. Here is my SQL code for creating table 1:
CREATE TABLE Employee_tbl (
EmployeeID int PRIMARY KEY IDENTITY,
LastName varchar(20) not null,
FirstName varchar(20) not null,
Age varchar(3) not null,
JobID int FOREIGN KEY REFERENCES JobTitle_tbl(JobID),
)
and here is table 2:
create table JobTitle_tbl(
JobID int PRIMARY KEY IDENTITY,
EEO1Classification varchar(50) not null,
Exempt_nonexempt_status varchar(20) not null,
)
I also have some insert statements:
INSERT INTO Employee_tbl
(LastName, FirstName, Age)
Values
('Smith', 'John', '50'),
...
and:
INSERT into JobTitle_tbl (EEO1Classification, Job_title, )
VALUES ('Office/Clerical', 'Accounting Clerk', ),
Why is the FK value showing null when I query table 1?
The foreign keys will not auto-populate, as it doesn't know what foreign key to use. You need to either insert the rows into the JobTitle_tbl table, then select the IDs back out (or use ##identity if using sql server)
select id from JobTitle_tbl where Job_title = ''
Another option would be to update your insert statements to include the primary key, although you'll have to allow identity inserts first.
SET IDENTITY_INSERT JobTitle_tbl ON
into the JobTitle_tbl (id, title) values (1, 'Manager')
SET IDENTITY_INSERT JobTitle_tbl OFF
In either case, you'll need to then update your first insert statements with the ID that you have.
insert into Employee_tbl (LastName, FirstName, JobID) values ('Smith', 'John', 1)

Adding a nullable foreign key

I have two tables built like this (this is just a simplified and non-proprietary example):
Person Table
-----------
p_Id, f_name, l_name
Job Table
----------
job_Id, job_desc
I want to add a foreign key column, Persons.job_Id, that can be nullable that references Job.job_Id (the PK) The reason is, the job may not be known in advance, so it could be null. Having an "Other" is not an option.
I had this so far but I'm getting "could not create constraint".
ALTER TABLE dbo.Person
ADD job_Id INT FOREIGN KEY (job_Id) REFERENCES dbo.Job(job_Id)
Try it in two steps:
ALTER TABLE dbo.Person ADD job_Id INT NULL;
ALTER TABLE dbo.Person ADD CONSTRAINT FL_JOB
FOREIGN KEY (job_Id) REFERENCES dbo.Job(job_Id);
Try it like this, WITH NOCHECK:
ALTER TABLE dbo.Person ADD job_Id INT NULL;
ALTER TABLE dbo.Person WITH NOCHECK ADD CONSTRAINT FL_JOB
FOREIGN KEY (job_Id) REFERENCES dbo.Job(job_Id);
Below is my solution with creating foreign key programmatically.
TestTable1 has substitute of FK that is either NULL or matches record in TestTable2.
TestTable2 has standard FK in TestTable1.
CREATE Table TestTable1 (ID1 int IDENTITY UNIQUE, ID2 int NULL);
GO
CREATE Table TestTable2 (ID2 int IDENTITY UNIQUE, ID1 int NOT NULL foreign key references TestTable1(ID1));
GO
CREATE procedure CreateTestRecord1 #ID2 int null AS
begin
if #iD2 IS NOT NULL AND NOT EXISTS(SELECT * from TestTable2 where ID2 = #ID2)
begin
RAISERROR('Cannot insert TestTable1 record. TestTable2 record with ID %d doesnt exist', 16, 1, #ID2);
return;
end
Insert into TestTable1(ID2) OUTPUT Inserted.ID1 Values(#ID2);
end
GO
CREATE procedure LinkTable1toTable2 #ID1 int, #ID2 int NULL as
begin
if #iD2 IS NOT NULL AND NOT EXISTS(SELECT * from TestTable2 where ID2 = #ID2)
begin
RAISERROR('Cannot update ID2 in TestTable1 record. TestTable2 record with ID %d doesnt exist', 16, 1, #ID2);
return;
end
update TestTable1 Set ID2=#ID2 where ID1=#ID1;
select ##ROWCOUNT;
endGO