Creating an update trigger is causing an error - sql

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.

Related

T-SQL (SQL Server 2016) trigger for column value alter, at Insert

I am working on a SSIS project of mine. I have successfully manage to load some csv's into my database (through Integration Services in VS) and now I am trying to create a trigger in the database.
All I want to happen is: when the number of the column second_road_class is -1 I want it to change into 6. I want the trigger to fire during the inserts.
My trigger code seems to debug ok in SSMS! But when I am later trying to insert the csv's again, the second_road_class column with -1 stays as it is.
Trigger code:
CREATE TRIGGER AccidentsTrigger
ON [Accidents]
INSTEAD OF INSERT
AS BEGIN
SET NOCOUNT ON
IF (SELECT [second_road_class] FROM INSERTED) LIKE '-1'
BEGIN
UPDATE [Accidents]
SET [second_road_class] = '6'
WHERE [second_road_class] = '-1'
END
END
Thanks for any help.
You could do this with an after insert trigger.
create trigger accidentstrigger on [accidents]
after insert as
begin;
set nocount on;
if exists (select 1 from inserted where [second_road_class] = '-1')
begin;
update a
set [second_road_class] = '6'
from [accidents] as a
inner join inserted i
/* change AccidentId to the Primary Key on accidents*/
on a.AccidentId = i.AccidentId
and i.[second_road_class] = '-1';
end;
end;
go
Example using the pilots table on rextester: http://rextester.com/XKX10184

UPDATE after INSERT for potentially multiple rows - not working

I have the following trigger which doesn't work and I'm not sure why.
The trigger should fire after an insert into the REFERRALS table and I've allowed for the possibility of multiple rows being inserted.
The value of ORIGINAL_PATIENT_ID in the REFERRALS table should be set to the value of PATIENT_ID in Inserted, but it just doesn't work, i.e. the value of ORIGINAL_PATIENT_ID remains NULL.
IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[updateOSC]'))
DROP TRIGGER [dbo].[updateOSC]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[updateOSC]
ON [dbo].[REFERRALS]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
IF (SELECT ORIGINAL_PATIENT_ID FROM Inserted) IS NULL
UPDATE [dbo].[REFERRALS]
SET ORIGINAL_PATIENT_ID = i.PATIENT_ID
FROM Inserted i
WHERE dbo.REFERRALS.PATIENT_ID = i.PATIENT_ID
END
GO
If you can have multiple rows being updated then IF (SELECT ORIGINAL_PATIENT_ID FROM Inserted) IS NULL doesn't make much sense to me as this will return multiple values which you cannot compare to NULL.
I think you will get your desired result by using
CREATE TRIGGER [dbo].[updateOSC]
ON [dbo].[REFERRALS]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
UPDATE [dbo].[REFERRALS]
SET
ORIGINAL_PATIENT_ID = i.PATIENT_ID
FROM
Inserted i
WHERE
dbo.REFERRALS.PATIENT_ID = i.PATIENT_ID AND i.ORIGINAL_PATIENT_ID IS NULL
END
GO

Trigger preventing a column from being updated

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

SQL Server 2008 created/last updated trigger issue

I am using this trigger in order to fill in the CreatedDate and LastUpdated columns (of type datetime) in a table:
CREATE TRIGGER trCreatedDate ON [LasMTest]
FOR INSERT
AS
UPDATE [LasMTest]
SET [LasMTest].Created = getdate(),
[LasMTest].LastModified = getdate()
FROM [LasMTest]
INNER JOIN Inserted ON [LasMTest].[ID] = Inserted.[ID]
GO
When I check the table, the dates are off by just a fraction of a second.
Created LastModified ID
2013-03-19 09:24:32.920 2013-03-19 09:24:32.930 4
2013-03-19 09:26:39.890 2013-03-19 09:26:39.900 5
How can I modify the trigger so that they are both the exact time?
It's the interaction of your two triggers that's causing the problem.
If, instead, you set both columns to default to getdate() and ditch your insert trigger, it should work - the INSERT won't also cause an UPDATE.
The alternative is to author your INSERT trigger as an INSTEAD OF trigger that performs an INSERT rather than an UPDATE (and thus, also, avoids the UPDATE trigger firing).
If you do want to write it as an INSTEAD OF trigger, it would be something like:
CREATE TRIGGER trCreatedDate ON [LasMTest]
INSTEAD OF INSERT
AS
INSERT INTO LasMTest (/* Column List */,Created,LastModified)
SELECT /* Column List */,getdate(),getdate() from inserted
GO
INSERTs into the triggering table in an INSTEAD OF trigger don't (thankfully) cause the trigger to be fired recursively. If ID is an IDENTITY column, then it should appear in the column lists above (it hasn't been generated yet).
Try this:
CREATE TRIGGER trCreatedDate ON [LasMTest]
FOR INSERT
AS
Declare #CurrentDate Datetime
Set #CurrentDate=getdate()
UPDATE [LasMTest] SET [LasMTest].Created=#CurrentDate,[LasMTest].LastModified=#CurrentDate
FROM [LasMTest] INNER JOIN Inserted ON [LasMTest].[ID]= Inserted.[ID]
GO
You basically want to avoid the UPDATE trigger when doing the update from INSERT. This is called Nested Triggers. One easy solution is to use CONTEXT_INFO() to communicate to the nested UPDATE trigger code that you are already in an INSERT trigger so it suppresses itself:
CREATE TRIGGER trCreatedDate ON [LasMTest]
FOR INSERT
AS
SET CONTEXT_INFO 0xDEADBEEF;
UPDATE [LasMTest]
SET [LasMTest].Created = getdate(),
[LasMTest].LastModified = getdate()
FROM [LasMTest]
INNER JOIN Inserted ON [LasMTest].[ID] = Inserted.[ID];
SET CONTEXT_INFO NULL;
GO
CREATE TRIGGER trModifiedDate ON [LasMTest]
FOR UPDATE
AS
DECLARE #context varbinary(128);
SET #context = CONTEXT_INFO();
IF #context is NULL
BEGIN
UPDATE [LasMTest]
SET [LasMTest].LastModified = getdate()
FROM [LasMTest]
INNER JOIN Inserted ON [LasMTest].[ID] = Inserted.[ID];
END
GO
However such an approach is fragile. An exception can leave the context_info set and suppress all subsequent UPDATE triggers in the session. This requires adding TRY/CATCH blocks. And you always run the risk of an application using CONTEXT_INFO for its own purposes and ruining your scheme.
Another solution is to make the UPDATE trigger smart. It can check the UPDATE(Created) inside the UPDATE trigger and suppress any action if the Created column was modified. This works by convention, because you know that the only place that updates the Created column is the INSERT trigger:
CREATE TRIGGER trModifiedDate ON [LasMTest]
FOR UPDATE
AS
IF NOT UPDATE(Created)
BEGIN
UPDATE [LasMTest]
SET [LasMTest].LastModified = getdate()
FROM [LasMTest]
INNER JOIN Inserted ON [LasMTest].[ID] = Inserted.[ID];
END
GO

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?