Trigger preventing a column from being updated - sql

I have created a trigger as below:
CREATE TRIGGER InsertUpdateATLastViewedMatch
ON dbo.AT_LastViewedMatch
FOR INSERT,UPDATE
AS
BEGIN
SET NOCOUNT ON;
-- update statements for trigger here
declare #id1 int, #matchFK int;
select #id1 = i.id from inserted i;
select #matchFK=i.AT_MatchFk from inserted i;
update dbo.AT_LastViewedMatch set matchId = #matchFK where id = #id1;
END
GO
While this trigger works- I am not able to update the value of the matchId column directly from SQLManager:
If I execute
UPDATE AT_LastViewedMatch set matchId='1179619' where id=5762
for example, I am still seeing the old value for matchId. I think the issue is related to the above trigger (since if I drop the trigger, it works). Is there a way to get past this?

From your trigger definition below, you have created it for insert and update
CREATE TRIGGER InsertUpdateATLastViewedMatch
ON dbo.AT_LastViewedMatch
FOR INSERT,UPDATE <-- Here
so essentially, whenever you are running an update statement from SSMS
UPDATE AT_LastViewedMatch set matchId='1179619' where id=5762
Your trigger performing the below line and setting it to old value
update dbo.AT_LastViewedMatch set matchId = #matchFK where id = #id1;
You need to remove that update from your trigger definition
CREATE TRIGGER InsertUpdateATLastViewedMatch
ON dbo.AT_LastViewedMatch
FOR INSERT

Related

Creating an update trigger is causing an error

There are two triggers; the first trigger is running perfectly but I want to add another trigger to the same table.
The second trigger is an after update trigger. Please check and tell my is it right or wrong or if we run this trigger it will run perfect or not
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[tr_issueBook]
ON [dbo].[IssueBooks]
FOR INSERT
AS
BEGIN
DECLARE #IsbnNumber varchar(255)
SELECT #IsbnNumber = ISBN_Number FROM inserted
UPDATE searchBooks
SET tbl_numberOfCopies = tbl_numberOfCopies - 1
WHERE tbl_IsbnBooks = #IsbnNumber
END
/******2nd Trigger ******/
CREATE TRIGGER [dbo].[tr_issueBook2]
ON [dbo].[IssueBooks]
AFTER UPDATE
AS
BEGIN
DECLARE #IsbnNumber varchar(255)
SELECT #IsbnNumber = BookTitle FROM updated
UPDATE searchBooks
SET tbl_numberOfCopies = [tbl_numberOfCopies] + 1
WHERE tbl_bookTitle = #IsbnNumber
END
My second trigger is throwing an error:
invalid object name updated
Both of your triggers are currently broken because you do not handle the case when the Inserted pseudo table has more or less rows than 1. You need to treat the Inserted pseudo table like you would any other table and perform set based operations on it instead of procedural logic.
-- INSERT Trigger - using the Inserted pseudo table
update searchBooks set
tbl_numberOfCopies = tbl_numberOfCopies - 1
where tbl_IsbnBooks in (select ISBN_Number from Inserted);
-- UPDATE Trigger - also using the Inserted pseudo table (There is no Updated table)
update searchBooks set
tbl_numberOfCopies = tbl_numberOfCopies + 1
where tbl_IsbnBooks in (select ISBN_Number from Inserted);
I highly recommend reading the Official Documentation.

Determine in value change before updating in Sql Server

I am working on updating of table
Table : User(id,name,Dob,createdDate,lastUpdatedDate)
I want to update lastUpdatedDate when there is change in Name column.
firstly I used update trigger but that is execute after updating of records
some helping link suggest me to use instead of Update trigger but if I use that one it will not update my records after trigger.
any solution?
well I found suitable solution for this problem
in after update trigger there are two table sets one is Inserted and other one is Deleted.
so by getting name from both table sets we can campare there values. if there value is same we will not update lastUpdatedDate and if there is any difference in values then we will update lastUdpatedDate
Create TRIGGER [dbo].[User__Update]
ON [dbo].[User]
AFTER Update
AS
BEGIN
SET NOCOUNT ON;
declare #AttributeValue varchar(max)
declare #OldAttributeValue varchar(max)
SELECT #AttributeValue = INSERTED.Name
FROM INSERTED
select #OldAttributeValue=Deleted.Name
FROM Deleted
if(#OldAttributeValue<>#AttributeValue)
BEGIN
IF UPDATE(Name)
BEGIN
update [User] set LastUpdatedDate=GetDate() where name =#AttributeValue
END
END
END

How to fire trigger after every insert in sql server table automatically?

I am new to SQL Server triggers. I am facing a problem recently that I have two tables named tbl_Item and tbl_changePrice. I want to update tbl_Item when tbl_changeprice is inserted new row. With this new row name same date data will be updated in tbl_item table.
Here is my trigger what is tried by me for updating the table:
Alter TRIGGER trgAfterInsert ON [dbo].[tbl_changePrice]
After insert
AS
declare #itemname int;
declare #saleprice decimal(18,2);
declare #buyprice decimal(18,2);
select #itemname=i.name from inserted i;
select #saleprice=i.saleprice from inserted i;
select #buyprice=i.pprice from inserted i;
update tbl_Item set sellingPrice= #saleprice, buyingPrice= #buyprice where name= #itemname
PRINT 'AFTER INSERT trigger fired.'
GO
To handle multiple rows being inserted at once - you need to rewrite your trigger to be able to deal with multiple rows in Inserted - something like this:
ALTER TRIGGER trgAfterInsert
ON [dbo].[tbl_changePrice]
AFTER INSERT
AS
UPDATE dbo.tbl_Item
SET sellingPrice = i.saleprice, buyingPrice = i.pprice
FROM Inserted i
WHERE tbl_Item.name = i.name
PRINT 'AFTER INSERT trigger fired.'
GO

Deleted Virtual table in SQL Server is empty ON Delete trigger

I am trying to invoke an ON Delete trigger event, but when I try to select row from the Deleted table, it is empty.
Is there any other way to get Id of row on which delete event has fired?
Code:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER TRIGGER [audit]
ON [dbo].[S_PARTY]
FOR DELETE
AS
-- Insert statements for trigger here
DECLARE #id nvarchar(50)
SET #id = (Select ROW_ID from deleted )
BEGIN
-- Insert statements for trigger here
INSERT INTO [dbo].[S_AMF_AUDIT_ITEM] (ROW_ID)
VALUES (#id);
END
When trigger fires on this, I am getting error as S_AMF_AUDIT_ITEM doesn't allow null values. So can you please help me this to get Id of table on which delete command executes?
Your trigger is broken.
It doesn't take into account that the DELETE statement might affect zero or more than one rows.
The issue with NULL could occur for the statement DELETE FROM [dbo].[S_PARTY] WHERE 1 = 0.
A fixed version would be
ALTER TRIGGER [audit]
ON [dbo].[S_PARTY]
FOR DELETE
AS
BEGIN
INSERT INTO [dbo].[S_AMF_AUDIT_ITEM]
(ROW_ID)
SELECT ROW_ID
FROM deleted;
END
A trigger can fire for 0..N deleted rows. For example:
delete YourTable
where 1=2
Would run a for delete trigger on YourTable. So a trigger has to be able to deal with zero or multiple rows. Consider rewriting your trigger like:
ALTER TRIGGER [audit] ON [dbo].[S_PARTY] FOR DELETE
AS
INSERT dbo.S_AMF_AUDIT_ITEM
(ROW_ID)
SELECT ROW_ID
FROM deleted
That will work for any number of inserted rows.

After insert, update trigger not running

I have two triggers After Insert or Update and Instead of Insert. It appears that the after trigger is not running or sending the correct data.
I have verified the correct operation of Z_UpdateStageTable stored procedure and the Instead of Insert trigger. Removing the Instead of Insert trigger doesn't have any affect. The After Insert, Update trigger was working correctly at one time, I haven't made any changes to it. I have tried deleting it and adding it, but it still doesn't run or have the correct data.
Any Ideas?
Instead of Insert:
ALTER TRIGGER [DeleteExistingFilter]
ON [dbo].[Z_MobileSyncFilters]
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM Z_MobileSyncFilters WHERE UserID = (SELECT UserID FROM INSERTED);
INSERT INTO Z_MobileSyncFilters
SELECT *
FROM INSERTED;
END
After Insert, Update:
TRIGGER [UpdateStageTable]
ON [dbo].[Z_MobileSyncFilters]
AFTER INSERT,UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #AllWos AS VARCHAR(5000);
DECLARE #PmWos AS VARCHAR(5000);
DECLARE #RepWos AS VARCHAR(5000);
SET #AllWos = (SELECT AllWos FROM INSERTED);
SET #RepWos = (SELECT AllWos FROM INSERTED);
SET #PmWos = (SELECT AllWos FROM INSERTED);
EXEC Z_UpdateStageTable #AllWos;
EXEC Z_UpdateStageTable #RepWos;
EXEC Z_UpdateStageTable #PmWos;
END
Is there a typo in the SET part of the AFTER trigger? You're selecting the same thing into three different variables.
Rather than confirming the behavior of Z_UpdateStageTable, I'd try to replace it with something dirt simple (a parameterless sql statement, say) to test whether the trigger's being called. It's possible that the sproc's not being called with what you think it's being called with.
You can add PRINT statements to the trigger and manually insert from ManagementStudio/Enterprise Manager to see where the trigger fails.
I see a problem when you insert multiple records in a single statement, as the SELECT FROM Inserted will return more than 1 record.
You can also update the SET statement to SELECT #Var = AllWos FROM Inserted
Hold on a second, if userid is your PK then Z_MobileSyncFilters will not have data yet, this is also an instead of trigger
this wholw block doesn't do anything really, why do you need this trigger?
DELETE FROM Z_MobileSyncFilters WHERE UserID = (SELECT UserID FROM INSERTED);
INSERT INTO Z_MobileSyncFilters
SELECT *
FROM INSERTED;
you second trigger is flawed because it will faile if you have a multi row operation
why do you have 2 insert trigger (1 instead 1 after) on this table?