Trigger After Update SQL - sql

I have Customer table. To simplify lets say i have two columns
Id
Name
I have a second table (Log) that I want to update ONLY when the Id column of my customer changes. Yes you heard me right that the primary key (Id) will change!
I took a stab but the NewId that gets pulled is the first record in the Customer table not the updated record
ALTER TRIGGER [dbo].[tr_ID_Modified]
ON [dbo].[customer]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF UPDATE (Id)
BEGIN
UPDATE [log]
SET NewId = Id
FROM customer
END
END

Many would make the argument that if you are changing PK values, you need to rethink the database/table design. However, if you need a quick & dirty fix, add a column to the customer table that is unique (and not null). Use this column to join between the [inserted] and [deleted] tables in your update trigger. Here's a sample script:
CREATE TABLE dbo.Customer (
Id INT CONSTRAINT PK_Customer PRIMARY KEY,
Name VARCHAR(128),
UQColumn INT IDENTITY NOT NULL CONSTRAINT UQ_Customer_UQColumn UNIQUE
)
CREATE TABLE dbo.[Log] (
CustomerId INT NOT NULL,
LogMsg VARCHAR(MAX)
)
INSERT INTO dbo.Customer
(Id, Name)
VALUES
(1, 'Larry'),
(2, 'Curley'),
(3, 'Moe')
INSERT INTO dbo.[Log]
(CustomerId, LogMsg)
VALUES
(1, 'Larry is cool'),
(1, 'Larry rocks'),
(2, 'Curley cracks me up'),
(3, 'Moe is mean')
CREATE TRIGGER [dbo].[tr_Customer_Upd]
ON [dbo].[customer]
FOR UPDATE
AS
BEGIN
UPDATE l
SET CustomerId = i.Id
FROM inserted i
JOIN deleted d
ON i.UQColumn = d.UQColumn
JOIN [Log] l
ON l.CustomerId = d.Id
END
SELECT *
FROM dbo.[Log]
UPDATE dbo.Customer
SET Id = 4
WHERE Id = 1
SELECT *
FROM dbo.[Log]

Related

Does if statement in after insert trigger matters for the performance in SQL Server? How if statement can be used for value validation?

I'm new to SQL Server, currently taking courses. My question is entirely for educational purposes.
I have an online artshop which includes following tables:
CREATE TABLE artproducts
(
prodid INT PRIMARY KEY IDENTITY (1,1),
catkey INT,
prodname VARCHAR(50) NOT NULL,
unitprice NUMERIC(10,2) NOT NULL,
stocknumbers INT NOT NULL,
available CHAR(3) NOT NULL DEFAULT 'Yes',
FOREIGN KEY(catkey) REFERENCES artcategory(catid)
);
CREATE INDEX idx_name ON artproducts(prodname);
INSERT INTO artproducts(catkey, prodname, unitprice, stocknumbers, available)
VALUES (3, 'Autumn landscape', 150, 2, 'Yes'),
(2, 'Brushes 5 stack', 15.95, 20, 'Yes'),
(2, 'Canvas 100x200', 40.50, 30, 'Yes'),
(1, 'Christmas ornament', 1.95, 30, 'Yes'),
(4, 'Copper carafe from Byzantium', 250.99, 3, 'Yes');
CREATE TABLE artorders
(
orderid INT PRIMARY KEY IDENTITY(1,1),
orderdate DATE NOT NULL,
prodkey INT NOT NULL,
custkey INT NOT NULL,
quantity INT NOT NULL,
orderprice NUMERIC(10,2) NOT NULL,
orderstatus VARCHAR(15) DEFAULT 'In progress',
FOREIGN KEY (prodkey) REFERENCES artproducts (prodid),
FOREIGN KEY (custkey) REFERENCES artcustomers (custid)
);
I created a trigger in SQL Server 2019 to update the price in artorders with the price from artproducts:
ALTER TRIGGER tr_artshop_FIU_checkprice
ON artorders
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE artorders
SET orderprice = prod.unitprice
FROM artproducts AS prod
INNER JOIN inserted AS i ON prod.prodid = i.prodkey
INNER JOIN artorders AS ord ON ord.prodkey = prod.prodid
END;
I tried to do it with if condition - to update the orderprice only when it is different from the one in artproducts. I tried using variables and subqueries, but then the trigger works only for single insert.
ALTER TRIGGER tr_artshop_FIU_checkprice
ON artorders
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #v_price NUMERIC (10,2);
DECLARE #ord_price NUMERIC (10,2);
SET #v_price = (SELECT prod.unitprice FROM artproducts AS prod INNER JOIN inserted AS i ON prod.prodid = i.prodkey)
SET #ord_price = (SELECT ord.orderprice FROM artorders AS ord INNER JOIN inserted AS i ON ord.orderid = i.orderid)
IF #ord_price != #v_price
BEGIN
UPDATE artorders
SET orderprice = prod.unitprice
FROM artproducts AS prod
INNER JOIN inserted AS i
ON prod.prodid = i.prodkey
INNER JOIN artorders AS ord
ON ord.prodkey = prod.prodid
END
END;
So, my question is whether it is better for performance to have if statement, or it doesn't matter?
But if it does, how can I use if condition working for multiple inserts.
Than You very much in advance!!!
It is better for "performance" to not have hidden bugs in your code.
The version with IF is assuming that inserted has only one row. This is a false assumption. In SQL Server, triggers are set-based. This code is broken -- and I really wish SQL Server could find a way to return a syntax error in this case.
Hence, performance has nothing to do with why the first version is better. In practice, I would expect the performance to be better too -- in the cases where the second doesn't generate an error (of the form: scalar subquery returned more than one row).

How to write a check to avoid the message "INSERT statement conflicted with the FOREIGN KEY constraint"?

I read and understood the entries in following asked question: INSERT statement conflicted with the FOREIGN KEY constraint
. I do get the point, however, I'm in this situation where I have around 1 Gb of records need to be inserted into a table, some of those records have conflicted foreign key. The query looks like this:
IF NOT EXISTS (SELECT * FROM [dbo].[tbl_R_TaskHistory] WHERE [TaskID] =
10000529)
BEGIN insert into [dbo].[tbl_History]
([TaskID],[UserID],[ActD],[RequestD],[No],[SignID],[Completed])
values (10000529,'A0000187',NULL,5738366,0,NULL,CAST(N'2011-03-16
04:53:37.210' AS DateTime)) END
The conflict ocurs on RequestID, so I was thinking there must be a way to make a check to avoid the error messages.
My point is that I want my query to check if the RequestID has not FOREIGN KEY constraint it will not insert this record and move to the next one.
If your query contains only one row, you can just expand the check like this:
IF NOT EXISTS (SELECT * FROM [dbo].[tbl_R_TaskHistory] WHERE [TaskID] = 10000529) AND EXISTS(SELECT 1 FROM [dbo].[...referencing table...] WHERE [RequestD] = 5738366)
BEGIN
insert into [dbo].[tbl_History] ([TaskID],[UserID],[ActD],[RequestD],[No],[SignID],[Completed])
values (10000529,'A0000187',NULL,5738366,0,NULL,CAST(N'2011-03-16 04:53:37.210' AS DateTime));
END
Anyway, if you are inserting many rows at the same time and for performance considerations, it will be better to store the values in buffer table. Something like this:
insert into #tbl_History ([TaskID],[UserID],[ActD],[RequestD],[No],[SignID],[Completed])
values (10000529,'A0000187',NULL,5738366,0,NULL,CAST(N'2011-03-16 04:53:37.210' AS DateTime))
,(...)
,(...)
,(...)
Then, just perform an inner join to your referencing table:
insert into [dbo].[tbl_History] ([TaskID],[UserID],[ActD],[RequestD],[No],[SignID],[Completed])
SELECT [TaskID],[UserID],[ActD],[RequestD],[No],[SignID],[Completed]
FROM #tbl_History A
INNER JOIN [dbo].[...referencing table...] B
ON A.[RequestD] = B.[RequestD];
This syntax also works
declare #a int = 5;
declare #b int = 18;
insert into sample (a, b)
select #a, #b
where not exists (select 1 from sample where b = #b)
and exists (select 1 from student where iden = #a)
This avoids creating a #temp
insert into sample (a, b)
select a, b
from ( values (5,19)
, (5,30)
, (5,31)
, (5,32)
, (7,41)
, (7,42)
) v(a,b)
where not exists (select 1 from sample where b = v.b)
and exists (select 1 from student where iden = v.a)

SQL Trigger that should update other table

I am trying to make a trigger that will update a table only if something is inserted in an other table
CREATE TABLE Purchases
(
PurchaseID INT IDENTITY NOT NULL PRIMARY KEY,
DateBought SMALLDATETIME,
Price MONEY CHECK (Price>0),
RealEstateID INT UNIQUE NOT NULL,
DealMadeByEmployeeID INT NOT NULL
);
INSERT INTO Purchases(DateBought, Price, RealEstateID, DealMadeByEmployeeID)
VALUES ('20161015 15:10:03','120000',3, 3); --Апартамент 170 квадратни метра
INSERT INTO Purchases(DateBought, Price, RealEstateID, DealMadeByEmployeeID)
VALUES ('20161219 13:13:30','200000',4, 3); --Къща 500 квадратни метра
INSERT INTO Purchases (Price,RealEstateID,DealMadeByEmployeeID)
VALUES ('130000',6,3); --непродаден апартамент
CREATE TABLE EmployeesSalary
(
EmployeeID INT NOT NULL PRIMARY KEY,
CurrentSalary MONEY DEFAULT 0,-- на процент
MonthlySalesMade INT DEFAULT 0,
MonthlyRentsMade INT DEFAULT 0
);
INSERT INTO EmployeesSalary (EmployeeID, CurrentSalary)
VALUES (1, '400');
INSERT INTO EmployeesSalary (EmployeeID, CurrentSalary)
VALUES (2, '400');
INSERT INTO EmployeesSalary (EmployeeID, CurrentSalary)
VALUES (3, '400');
CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate --при INSERT в Purchases таблицата
ON Purchases
AFTER INSERT
AS
BEGIN
UPDATE EmployeesSalary
SET EmployeesSalary.MonthlySalesMade=EmployeesSalary.MonthlySalesMade+1
WHERE EmployeesSalary.EmployeeID IN (SELECT inserted.DealMadeByEmployeeID FROM inserted)
END
but based on the IDs.
My code doesn't get any errors but the trigger doesn't seem to work. What is my mistake?
https://postimg.org/image/rot0xcriv/
You should use an INNER JOIN there:
CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate --при INSERT в Purchases таблицата
ON Purchases
AFTER INSERT
AS
BEGIN
UPDATE ES
SET ES.MonthlySalesMade = ES.MonthlySalesMade+1
FROM EmployeesSalary ES
INNER JOIN INSERTED I
ON ES.EmployeeID = I.DealMadeByEmployeeID;
END
It won't work if there are multiple updates unless NOCOUNT is SET to ON:
CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate
ON Purchases
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON -- new line of code
UPDATE EmployeesSalary
SET EmployeesSalary.MonthlySalesMade=EmployeesSalary.MonthlySalesMade+1
WHERE EmployeesSalary.EmployeeID IN (SELECT inserted.DealMadeByEmployeeID FROM inserted)
END
You can also use the EXISTS operator.
Also beaware of the possible NULLS in MonthlySalesMade column, +1 update will not work if there is a null values in that column.
CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate
ON Purchases
AFTER INSERT
AS
BEGIN
UPDATE EmployeesSalary
SET MonthlySalesMade = ISNULL(MonthlySalesMade, 0)+1
WHERE EXISTS (SELECT 1
FROM inserted
WHERE EmployeesSalary.EmployeeID = inserted.DealMadeByEmployeeID )
END

UPDATE source table, AFTER Grouping?

I have a table (source) with payments for a person - called 'Item' in the example below.
This table will have payments for each person, added to it over a period.
I then generate invoices, which basically takes all the payments for a particular person, and sums them up into a single row.
This must be stored in an invoice table, for auditing reasons.
I do this in the example below.
What I am missing, though, as I am not sure how to do it, is that each payment, once assigned to the Invoice table, needs to had the Invoice ID that it was assigned to, stored in the Items table.
So, see the example below:
CREATE TABLE Items
(
ID INT NOT NULL IDENTITY(1,1),
PersonID INT NOT NULL,
PaymentValue DECIMAL(16,2) NOT NULL,
AssignedToInvoiceID INT NULL
)
CREATE TABLE Invoice
(
ID INT NOT NULL IDENTITY(1,1),
PersonID INT NOT NULL,
Value DECIMAL(16,2)
)
INSERT INTO Items (PersonID, PaymentValue) VALUES (1, 100)
INSERT INTO Items (PersonID, PaymentValue) VALUES (2, 132)
INSERT INTO Items (PersonID, PaymentValue) VALUES (2, 65)
INSERT INTO Items (PersonID, PaymentValue) VALUES (1, 25)
INSERT INTO Items (PersonID, PaymentValue) VALUES (3, 69)
SELECT * FROM Items
INSERT INTO Invoice (PersonID, Value)
SELECT PersonID, SUM(PaymentValue) FROM Items
WHERE AssignedToInvoiceID IS NULL
GROUP BY PersonID
SELECT * FROM Invoice
DROP TABLE Items
DROP TABLE Invoice
What I need to do is then update the Items table, to say that the first row has been assigned to Invoice.ID 1, row two was assigned to Invoice ID 2. Row 3, was assigned to Invoice ID 2 as well.
Note, there are many other columns in the table. This is a basic example.
Simply, I need to record which invoice, each source row was assigned to.
The key thing here to ensure payments are correctly linked to invoices is to ensure that:
A: No updates are made to Items between reading the unassigned items and updating AssignedToInvoiceID.
B: No new invoices are created with the Items being process before updating AssignedToInvoiceID.
As you are updating two tables it will have to be a two step process. To ensure A it will need to be run in a transaction with a least REPEATABLE READ isolation. To ensure B requires a transaction with SERIALIZABLE isolation. See SET TRANSACTION ISOLATION LEVEL
It can be done like this:
BEGIN TRAN
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
DECLARE #newInvoices TABLE (PersonID INT, InvoiceID INT)
INSERT INTO Invoice (PersonID, Value)
OUTPUT inserted.ID, inserted.PersonID INTO #newInvoices(InvoiceID, PersonID)
SELECT PersonID, SUM(PaymentValue) FROM Items
WHERE AssignedToInvoiceID IS NULL
GROUP BY PersonID
UPDATE Items
SET AssignedToInvoiceID = InvoiceID
FROM Items
INNER JOIN #newInvoices newInvoice ON newInvoice.PersonID = Items.PersonID
WHERE AssignedToInvoiceID IS NULL
COMMIT
An alternative if you are using SQL Server 2012 or later is to use the SEQUNCE object, this will allow the Items to be assigned new invoice IDs before the Invoices are created, reducing the locking required.
It works like this:
-- Run once with your table setup.
CREATE SEQUENCE InvoiceIDs AS INT START WITH 1 INCREMENT BY 1
CREATE TABLE Items
(
ID INT NOT NULL IDENTITY(1,1),
PersonID INT NOT NULL,
PaymentValue DECIMAL(16,2) NOT NULL,
AssignedToInvoiceID INT NULL
)
CREATE TABLE Invoice
(
-- No longer a IDENTITY column
ID INT NOT NULL,
PersonID INT NOT NULL,
Value DECIMAL(16,2)
)
BEGIN TRAN
DECLARE #newInvoiceLines TABLE (PersonID INT, InvoiceID INT, PaymentValue DECIMAL(16,2))
-- Reading and updating AssignedToInvoiceID happens in one query so is thread safe.
UPDATE Items
SET AssignedToInvoiceID = newInvoices.InvoiceID
OUTPUT inserted.PersonID, inserted.AssignedToInvoiceID, inserted.PaymentValue
INTO #newInvoiceLines(PersonID, InvoiceID, PaymentValue)
FROM Items
INNER JOIN (
SELECT PersonID, NEXT VALUE FOR InvoiceIDs AS InvoiceID
FROM Items
GROUP BY PersonID
) AS newInvoices ON newInvoices.PersonID = Items.PersonID
WHERE Items.AssignedToInvoiceID IS NULL
INSERT INTO Invoice (ID, PersonID, Value)
SELECT InvoiceID, PersonID, SUM(PaymentValue) FROM #newInvoiceLines
GROUP BY PersonID, InvoiceID
COMMIT
You will still want to use a transaction to ensure the Invoice gets created.
Based on what I understand, you could run an update from join after you have inserted records into Invoices table, like so:
update items
set assignedtoinvoiceid = v.id
from
items m
inner join invoice v on m.personid = v.personid
Demo
Each time you do an invoice "run", select the most recent invoice for each person something like,
update items
set AssignedToInvoiceID = inv.id
from
(select personid, max(id) id
from invoice
group by personid) inv
where items.personid = inv.personid
and AssignedToInvoiceID is null
this assumes that AssignedToInvoiceID is null when it isn't populated, if it gets defaulted to an empty string or something then you would need to change the where condition.
1) Get MAX(ID) from Invoice table before inserting new rows from Items table. Store this value into a variable: #MaxInvoiceID
2) After inserting records into Invoice table, update AssignedToInvoiceID in Items table with Invoice.ID>#MaxInvoiceID
Refer below code:
CREATE TABLE #Items
(
ID INT NOT NULL IDENTITY(1,1),
PersonID INT NOT NULL,
PaymentValue DECIMAL(16,2) NOT NULL,
AssignedToInvoiceID INT NULL
)
CREATE TABLE #Invoice
(
ID INT NOT NULL IDENTITY(1,1),
PersonID INT NOT NULL,
Value DECIMAL(16,2)
)
DECLARE #MaxInvoiceID INT;
SELECT #MaxInvoiceID=ISNULL(MAX(ID),0) FROM #Invoice
SELECT #MaxInvoiceID
INSERT INTO #Items (PersonID, PaymentValue) VALUES (1, 100)
INSERT INTO #Items (PersonID, PaymentValue) VALUES (2, 132)
INSERT INTO #Items (PersonID, PaymentValue) VALUES (2, 65)
INSERT INTO #Items (PersonID, PaymentValue) VALUES (1, 25)
INSERT INTO #Items (PersonID, PaymentValue) VALUES (3, 69)
SELECT * FROM #Items
INSERT INTO #Invoice (PersonID, Value)
SELECT PersonID, SUM(PaymentValue)
FROM #Items
WHERE AssignedToInvoiceID IS NULL
GROUP BY PersonID
SELECT * FROM #Invoice
UPDATE Itm
SET Itm.AssignedToInvoiceID=Inv.ID
FROM #Items Itm
JOIN #Invoice Inv ON Itm.PersonID=Inv.PersonID AND Itm.AssignedToInvoiceID IS NULL AND Inv.ID>#MaxInvoiceID
SELECT * FROM #Items
DROP TABLE #Items
DROP TABLE #Invoice

inserting into A errors because of a foreign key contraint issue

Can someone help explain this to me and resolve it?
http://sqlfiddle.com/#!6/2adc7/9
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tblMobileForms_tblForms". The conflict occurred in database "db_6_2adc7", table "dbo.tblForms", column 'fm_id'.: insert into tblMobileForms(fm_name) values ('lol')
My schema has the ID from tblMobileForms be a foreign key to tblForms.fm_id
To do what you are trying to do you cannot set up the FK on tblMobileForms as an identity. See my fiddle below for more information.
http://sqlfiddle.com/#!6/be6f7/2
Alternatively what you could do is to have tblMobileForms have it's own separate surrogate key and have a different FK column to the tblForms table.
The PK on the tblMobileForms table has the same name as the FK on the same table. Seeing the PK is an IDENTITY column, you can end up with non-matching values.
In my fiddle, the tblForms table contained IDs in the upper 60s. Running the INSERT in the child table would add a record with id 1, which does not exist in the parent table.
I'd create a new row in the tblMobileForms table, and reference that to the parent table.
You could use an INSTEAD OF trigger to apply a random ID to each mobile form as it is inserted:
CREATE TRIGGER dbo.tblMobileForms_Insert
ON dbo.tblMobileForms
INSTEAD OF INSERT
AS
BEGIN
DECLARE #Inserted TABLE (fm_ID INT, fm_html_file VARBINARY(MAX), fm_name NVARCHAR(50));
INSERT #Inserted (fm_ID, fm_html_File, fm_Name)
SELECT fm_ID, fm_html_File, fm_Name
FROM inserted;
IF EXISTS (SELECT 1 FROM #Inserted WHERE fm_ID IS NULL)
BEGIN
WITH NewRows AS
( SELECT fm_ID, fm_html_File, fm_Name, RowNumber = ROW_NUMBER() OVER (ORDER BY fm_name)
FROM #Inserted
WHERE fm_ID IS NULL
), AvailableIDs AS
( SELECT fm_ID, RowNumber = ROW_NUMBER() OVER (ORDER BY fm_ID)
FROM tblForms f
WHERE NOT EXISTS
( SELECT 1
FROM tblMobileForms m
WHERE f.Fm_ID = m.fm_ID
)
AND NOT EXISTS
( SELECT 1
FROM inserted i
WHERE f.fm_ID = i.fm_ID
)
)
UPDATE NewRows
SET fm_ID = a.fm_ID
FROM NewRows n
INNER JOIN AvailableIDs a
ON a.RowNumber = n.RowNumber
IF EXISTS (SELECT 1 FROM #Inserted WHERE fm_ID IS NULL)
BEGIN
RAISERROR ('Not enough free Form IDs to allocate an ID to the inserted rows', 16, 1);
RETURN;
END
END
INSERT dbo.tblMobileForms (fm_ID, fm_html_File, fm_Name)
SELECT fm_ID, fm_html_file, fm_name
FROM #Inserted
END
When each row is inserted the trigger will check for the next available ID in tblForms and apply it sequentially to the inserted rows where fm_id is not specified. If there are no free ID's in tblForms then the trigger will throw an error so a 1 to 1 relationship is maintained (The error would be thrown anyway since tblMobileForms.fm_id is also a PK).
N.b. this requires tblForms.fm_ID to just be an int column, and not identity.