SQL Server 2000 trigger on insert - sql-server

I need to create a trigger for my table that will contain millions of inserts.
That trigger will send an email (already done) to me saying that table is being powered.
That email should be send only once when the insert starts (one a day).
In other words, I wanna do this :
Create trigger on table T1 on FIRST INSERT; EXEC my procedure to send email
Not being a developer I really don't know how to write this...
Thank you for you help.

You cannot easily do a ON FIRST INSERT trigger.
What you could do is this:
create a normal ON INSERT trigger that sends you the email
at the end of that trigger, disable that trigger:
ALTER TABLE dbo.YourTable DISABLE TRIGGER YourTriggerNameHere
This would prevent the trigger from firing over and over again and sending you tons of e-mail.
Then, you'd also need a SQL Agent job that would at night enable that trigger again - so that it could fire again for the first insert of the next day.
Update: OK, so in your case it would be:
CREATE TRIGGER sendMail
ON MyTable AFTER INSERT
AS
EXEC master.dbo.MyProcedure
ALTER TABLE dbo.MyTable DISABLE TRIGGER sendMail
and in your SQL Agent job at night, you'd need:
ALTER TABLE dbo.MyTable ENABLE TRIGGER sendMail

Why not have a table that you also update in your trigger with the last time that an email was sent out? Then you could query this table in the trigger and decide whether you want to send out another on
create trigger tr
on tab after insert
as
begin
declare #today datetime;
set #today = cast(convert(varchar(32), getdate(), 112) as datetime);
if not exists(select * from logtab where logdate = #today)
begin
-- Send the email
exec sendMail
-- Update Log Table
update logtab
set logdate = #today
end
end
GO

You cant directly fire a trigger on first update.
You can however have a table that log when you send emails and for what table, and in the trigger you can ask if there is a record there for that day dont send it, if its not, insert in that table and call your sp.
Your sp could do this check also.

Related

Copy Trigger stops row being inserted

I am trying to create a trigger that copies newly inserted data from one table and inserts it into another table in a linked server.
However, when the trigger is created it stops the data appearing in the original table until the trigger is deleted and also does not even copy it over to the other table in the linked server either.
Here is my trigger
GO /****** Object: Trigger [dbo].[CopyTMSINFO] Script Date: 12/07/2022 12:53:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[CopyTMSINFO]
ON [dbo].[d_iface_att]
After INSERT
AS DECLARE #EmpID nvarchar(MAX),
#datetime datetime
SELECT #EmpID = ins.emp_id FROM INSERTED ins;
SELECT #datetime = ins.date_and_time FROM INSERTED ins;
INSERT INTO [MAL-HQ-SQL01].[MallaghanApp].[dbo].[EmployeeClockIn] (Id,Employee,TASDateTimeStart,TMSDateTime,JobType)
VALUES ( NEWID(),#EmpID,0,#datetime, 'TMS')
Any help would be greatly appreciated as i dont know much about this stuff and i am really confused.
There are two issues with your trigger:
You need to use SET NOCOUNT ON to prevent the "rows done" messing up exepcted resultsets in some client drivers.
You need to take into account multiple (or zero) rows in the inserted table.
CREATE OR ALTER TRIGGER [dbo].[CopyTMSINFO]
ON [dbo].[d_iface_att]
AFTER INSERT
AS
SET NOCOUNT ON;
IF NOT EXISTS (SELECT 1 FROM inserted)
RETURN;
INSERT INTO [MAL-HQ-SQL01].MallaghanApp.dbo.EmployeeClockIn
(Id, Employee, TASDateTimeStart, TMSDateTime, JobType)
SELECT
NEWID(),
ins.emp_id,
0,
ins.date_and_time,
'TMS'
FROM inserted ins;
However, inserting into a linked server using a trigger is very bad form anyway. What happens if the remote server is offline?
You should instead use other replication methods, such as the remote server pulling data from this server using an Agent Job.

What's the workaround to pass parameters to triggers?

I have a trigger in "Contracts" and I also have a table called "Audits" (self explanatory).
Everything is working fine. If I insert, edit or delete, a row is inserted into Audits table by the trigger...
The problem here is that Trigger does not accept parameters... and I have a table column called "TriggeredBy" inside of the Audits table... which is supposed to have the User's ID (whoever did the insert, delete or UPDATE).
Is there a workaround that I can use so I can pass that value to that trigger?
If you have the db connection opened for the duration of the application, you can keep track of who is associated with the current db session by having a table with session if, user id.
SessionId int,
UserId varchar(20)
At login time, use ##SPID to store the session ID and associated user.
The trigger can then use ##SPID and retrieve the user ID from the table and insert it into the log table.
Option 2:
Use an application role. Allow users to connect to SQL server database using Windows Integrated Security. Call sp_setapprole to set the role. Users should be given no access to any table. The app role should have insert update delete.
You can now determine the user in your trigger.
If the desktop application used Windows authentication, you could simply use ORIGINAL_LOGIN() or SUSER_SNAME() to get the end user account name in trigger code.
With a shared SQL login, one method is to store the end user name in SQL session context for use by the trigger. Session context allows you to store name/value pairs using the sp_set_session_context procedure and read current session values with the SESSION_CONTEXT function. Call sp_set_session_context with the current user name after opening a new SQL connection so that it can be used by triggers to identify the end user.
Example T-SQL code below. Also, see this answer for other methods to set/use session level values.
CREATE TRIGGER TR_YourTable
ON dbo.YourTable
FOR INSERT, UPDATE, DELETE
AS
DECLARE #TriggeredBy sysname = COALESCE(CAST(SESSION_CONTEXT(N'end-user-name') AS sysname), N'unknown');
IF EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
BEGIN
INSERT INTO dbo.YourAuditTable (Action, SomeColumn, TriggeredBy)
SELECT 'updated', SomeColumn, #TriggeredBy
FROM deleted;
END
ELSE
BEGIN
IF EXISTS(SELECT 1 FROM inserted)
BEGIN
INSERT INTO dbo.YourAuditTable (Action, SomeColumn, TriggeredBy)
SELECT 'inserted', SomeColumn, #TriggeredBy
FROM inserted;
END
ELSE
BEGIN
INSERT INTO dbo.YourAuditTable (Action, SomeColumn, TriggeredBy)
SELECT 'deleted', SomeColumn, #TriggeredBy
FROM deleted;
END;
END;
GO
--Example T-SQL usage. Queries should be parameterized in application code.
EXEC sp_set_session_context N'end-user-name', N'me';
INSERT INTO dbo.YourTable (SomeColumn) VALUES('example');
GO

Trigger doesn't fire when row is inserted

I built a trigger in SQL Server to execute a stored procedure when a new row is inserted into the table Balance Data, but the trigger doesn't get fired. I don't know what I am doing wrong or what is happening.
This is the script:
CREATE TRIGGER [dbo].[SP_Trigger]
ON [dbo].[BalanceData]
FOR INSERT
AS
BEGIN
SET NOCOUNT ON;
Exec Schenck.dbo.spCopyData
END
I assume that you are using Transact-SQL.
According to the documentation, FOR INSERT triggers are synonymous with AFTER INSERT triggers by default. This should fire after you have inserted your data into [dbo].[BalanceData].
I would firstly confirm that the data has been inserted successfully (i.e. no check constraint violations, etc) and then confirm what Schenck.dbo.spCopyData is doing. You have turned ROWCOUNT off in the trigger, so perhaps this has given you the illusion that nothing happened.

Execute stored procedure from a Trigger after a time delay

I want to call stored procedure from a trigger,
how to execute that stored procedure after x minutes?
I'm looking for something other than WAITFOR DELAY
thanks
Have an SQL Agent job that runs regularly and pulls stored procedure parameters from a table - the rows should indicate also when their run of the stored procedure should occur, so the SQL Agent job will only pick rows that are due/slightly overdue. It should delete the rows or mark them after calling the stored procedure.
Then, in the trigger, just insert a new row into this same table.
You do not want to be putting anything in a trigger that will affect the execution of the original transaction in any way - you definitely don't want to be causing any delays, or interacting with anything outside of the same database.
E.g., if the stored procedure is
CREATE PROCEDURE DoMagic
#Name varchar(20),
#Thing int
AS
...
Then we'd create a table:
CREATE TABLE MagicDue (
MagicID int IDENTITY(1,1) not null, --May not be needed if other columns uniquely identify
Name varchar(20) not null,
Thing int not null,
DoMagicAt datetime not null
)
And the SQL Agent job would do:
WHILE EXISTS(SELECT * from MagicDue where DoMagicAt < CURRENT_TIMESTAMP)
BEGIN
DECLARE #Name varchar(20)
DECLARE #Thing int
DECLARE #MagicID int
SELECT TOP 1 #Name = Name,#Thing = Thing,#MagicID = MagicID from MagicDue where DoMagicAt < CURRENT_TIMESTAMP
EXEC DoMagic #Name,#Thing
DELETE FROM MagicDue where MagicID = #MagicID
END
And the trigger would just have:
CREATE TRIGGER Xyz ON TabY after insert
AS
/*Do stuff, maybe calculate some values, or just a direct insert?*/
insert into MagicDue (Name,Thing,DoMagicAt)
select YName,YThing+1,DATEADD(minute,30,CURRENT_TIMESTAMP) from inserted
If you're running in an edition that doesn't support agent, then you may have to fake it. What I've done in the past is to create a stored procedure that contains the "poor mans agent jobs", something like:
CREATE PROCEDURE DoBackgroundTask
AS
WHILE 1=1
BEGIN
/* Add whatever SQL you would have put in an agent job here */
WAITFOR DELAY '00:05:00'
END
Then, create a second stored procedure, this time in the master database, which waits 30 seconds and then calls the first procedure:
CREATE PROCEDURE BootstrapBackgroundTask
AS
WAITFOR DELAY '00:00:30'
EXEC YourDB..DoBackgroundTask
And then, mark this procedure as a startup procedure, using sp_procoption:
EXEC sp_procoption N'BootstrapBackgroundTask', 'startup', 'on'
And restart the service - you'll now have a continuously running query.
I had kind of a similar situation where before I processed the records inserted into the table with the trigger, I wanted to make sure all the relevant related data in relational tables was also there.
My solution was to create a scratch table which was populated by the insert trigger on the first table.
The scratch table had a updated flag, (default set to 0), and an insert get date() date field, and the relevant identifier from the main table.
I then created a scheduled process to loop over the scratch table and perform whatever process I wanted to perform against each record individually, and updating the 'updated flag' as each record was processed.
BUT, here is where I was a wee bit clever, in the loop over process looking for records in the scratch table that had a update flag = 0, I also added the AND clause of AND datediff(mi, Updated_Date, getdate())> 5. So the record would not actually be processed until 5 minutes AFTER it was inserted into the scratch table.

SQL Server: pause a trigger

I am working with SQL Server 2005 and I have trigger on a table that will copy an deletions into another table. I cannot remove this trigger completely. My problem is that we have now developed an archiving strategy for this table. I need a way of "pausing" a trigger when the stored proc that does the archiving runs.
A little more detail would be useful on how the procedure is accessing the data, but assuming you are just getting the data, then deleting it from the table and wish to disable the trigger for this process, you can do the following
DISABLE TRIGGER trg ON tbl;
then
ENABLE TRIGGER trg ON tbl;
for the duration of the procedure.
This only works for SQL 2005+
An alternative method is to use Context_Info to disable it for a single session, while allowing other sessions to continue to fire the trigger.
Context_Info is a variable which belongs to the session. Its value can be changed using SET Context_Info.
The trigger will mostly look like this:
USE AdventureWorks;
GO
-- creating the table in AdventureWorks database
IF OBJECT_ID('dbo.Table1') IS NOT NULL
DROP TABLE dbo.Table1
GO
CREATE TABLE dbo.Table1(ID INT)
GO
-- Creating a trigger
CREATE TRIGGER TR_Test ON dbo.Table1 FOR INSERT,UPDATE,DELETE
AS
DECLARE #Cinfo VARBINARY(128)
SELECT #Cinfo = Context_Info()
IF #Cinfo = 0x55555
RETURN
PRINT 'Trigger Executed'
-- Actual code goes here
-- For simplicity, I did not include any code
GO
If you want to prevent the trigger from being executed you can do the following:
SET Context_Info 0x55555
INSERT dbo.Table1 VALUES(100)
Before issuing the INSERT statement, the context info is set to a value. In the trigger, we are first checking if the value of context info is the same as the value declared. If yes, the trigger will simply return without executing its code, otherwise the trigger will fire.
source: http://www.mssqltips.com/tip.asp?tip=1591
if DISABLE TRIGGER/ENABLE TRIGGER is not an option for some reason, you can create a table with a single row which will serve as a flag for the trigger.

Resources