SQL Trigger code run without error but no Out put - sql-server

I have two data base in same server TEST1 and TEST2
In TEST1 i have a table called dbo.TB_EVENT_LOG
columns are
[nEventLogIdn]
[nDateTime]
[nReaderIdn]
[nEventIdn]
[nUserID]
[nIsLog]
[nTNAEvent]
[nIsUseTA]
[nType]
and in Test2 i have a table called dbo.AccessLog
columns are
[RCDID]
[EmployeeID]
[LogDate]
[LogTime]
[TerminalID]
[InOut]
What i want to do is fire a trigger when ever any data is inset or update to test1 dbo.TB_EVENT_LOG. And insert the data from specific columns of dbo.TB_EVENT_LOG( nDateTime, nReaderIdn, nUserID) to dbo.AccessLog (LogDate, TerminalID, EmployeeID)
The trigger running in dbo.TB_EVENT_LOG Table
Here is the trigger code i have so far
USE [test1]
GO
/****** Object: Trigger [dbo].[coveter] Script Date: 11/18/2018 2:25:13 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
-- Create date: 18/11/2018
-- Description:
-- =============================================
ALTER TRIGGER [dbo].[coveter]
ON [dbo].[TB_EVENT_LOG]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
insert into test2.dbo.AccessLog
(
[LogDate],
[LogTime],
[TerminalID],
[EmployeeID]
)
select [nDateTime], [nDateTime], [nReaderIdn],[nUserID] from dbo.TB_EVENT_LOG
END
The Code run without any error but i couldn't get the result i want. Any help?
Thank you in advance.

Related

Fire SQL Trigger When Column Value Changes

I am adding the date to a column in SQL when the 'workstatus' is 'completed', but my problem is, when I open and save the same job again in the software, it runs the trigger and changes the date again to a new value which I don't want.
I want the trigger to run only if the 'workstatus' value is something else than 'completed'.
GO
/****** Object: Trigger [dbo].[TRJCD_JOBREQUEST] Script Date: 06/25/2021 15:49:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[TRJCD_JOBREQUEST] ON [dbo].[TBL_JOBREQUEST]
AFTER UPDATE,INSERT
AS
if (Update (workstatus))
begin
DECLARE #Jobcompletiondate datetime
DECLARE #workstatus VARCHAR(15)
DECLARE #jobid int
select #workstatus = workstatus from inserted
select #jobid = jobid from inserted
select #Jobcompletiondate = GETDATE()
begin
if #workstatus='Completed'
update TBL_JOBREQUEST set JobCompDate=#Jobcompletiondate where jobid = #jobid
end
end
The following is how you should construct your trigger.
There is no need to assign any values to variables, triggers fire once per batch and always operate on the set of updated rows.
If you update a status to Completed you need to check it's not currently Completed, also if you want to retain the first JobCompDate even if the status is amended afterwards simply use a case expression to only update the column where it's currently NULL.
create or alter trigger [dbo].[TRJCD_JOBREQUEST] on [dbo].[TBL_JOBREQUEST]
after update,insert
as
if ##RowCount=0 return
set nocount on
if Update (workstatus)
begin
update t set
t.JobCompDate=case when t.JobCompDate is null then GetDate() else t.JobCompDate end
from inserted i join TBL_JOBREQUEST t on t.jobid=i.jobid
where i.workstatus='Completed'
and not exists (
select * from deleted d
where d.jobid=i.jobid and d.workstatus=i.workstatus
)
end
Please note that I do not have your data set, so I'm unable to test the trigger, however, based on what you provided in your question, I believe this is the answer you are seeking:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[TRJCD_JOBREQUEST] ON [dbo].[TBL_JOBREQUEST]
AFTER UPDATE,INSERT
AS
if (Update (workstatus))
begin
DECLARE #Jobcompletiondate datetime
DECLARE #currentworkstatus VARCHAR(15)
DECLARE #oldworkstatus VARCHAR(15)
DECLARE #jobid int
select #oldworkstatus = workstatus from deleted
select #currentworkstatus = workstatus from inserted
select #jobid = jobid from inserted
select #Jobcompletiondate = GETDATE()
begin
if #currentworkstatus='Completed' and #oldworkstatus <> 'Completed'
update TBL_JOBREQUEST set JobCompDate=#Jobcompletiondate where jobid = #jobid
end
end
You needed to check if the deleted workstatus does not equal Completed and only then should the trigger fire.

I made a sp that works perfectly, but when I create the trigger to execute it ,it gives error

The SP makes an update on the EmpAttendance table column SubDiario when the change in the table EmpSalary column SubDiario
and it works, but when I try to trigger the sp "EXEC [dbo]. [sp_SubMensal_update] gives an error
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).
the SP
USE [MiniPayroll]
GO
/****** Object: StoredProcedure [dbo].[SubMensal_update] Script Date: 14-04-2021 15:46:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[SubMensal_update]
AS
BEGIN
update dbo.EmpAttendance set
EmpAttendance.SubDiario= EmpSalary.SubDiario
from dbo.EmpSalary
join EmpAttendance on EmpSalary.EmpId=EmpAttendance.EmpId
where EmpAttendance.time_registered > getdate() -1
END
The Trigger
USE [MiniPayroll]
GO
/****** Object: Trigger [dbo].[update_SubMensal] Script Date: 14-04-2021 16:32:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER TRIGGER [dbo].[update_SubMensal]
ON [dbo].[EmpAttendance]
AFTER INSERT,UPDATE,DELETE AS BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
EXEC [dbo].[SubMensal_update]
END
thanks

how to access a column of a table via foreign key?

I am new in SQL server and having trouble with this trigger code. Can you please tell me what is wrong with this line: set NazivFirme=(select NazivFirme from inserted)... This is where I get an error.
USE [BazaPreduzece]
GO
/****** Object: Trigger [dbo].[promenaNazivaFirme] Script Date: 2017-03-28 5:29:47 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER trigger [dbo].[promenaNazivaFirme]
on [dbo].[Firma]
AFTER UPDATE
as
declare #FirmaID int
select #FirmaID=FirmaID from inserted
if update (NazivFirme)
begin
alter table Vlasnik disable trigger zabranaAzuriranjaNazivaFirme
update [dbo].[Vlasnik]
set NazivFirme=(select NazivFirme from inserted)
where FirmaID=#FirmaID
alter table Vlasnik enable trigger zabranaAzuriranjaNazivaFirme
end
That's theFirma and the Vlasnik tables...

SQL Server Trigger fires unexplainably

I've got a trigger on a table. It's a very simple trigger, set to after insert, send me an e-mail. Since I've put that trigger on, I've been sent e-mails by the system every 5 or 6 minutes or so. There is just one problem.
Whenever I receive an e-mail, the table is EMPTY
Here is my trigger
USE [didaprod]
GO
/****** Object: Trigger [dbo].[Caseplayer_CaseId_Restore_insert_mail] Script Date: 09-08-2016 11:59:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE trigger [dbo].[Caseplayer_CaseId_Restore_insert_mail] on [dbo].[Caseplayer_CaseId_Restore]
AFTER INSERT
as
SET NOCOUNT ON
declare #tekst nvarchar(500);
set #tekst = 'caseid sat til null på caseplayer! Tjek Caseplayer_CaseId_Restore tabel!' + convert(varchar,getdate(),105);
EXEC msdb.dbo.sp_send_dbmail #profile_name = 'Mail',
#recipients = 'kk#byggeevaluering.dk',
#subject = 'CASEID SAT TIL NULL!!!',
#body = #tekst
SET NOCOUNT OFF
GO
I've tried to manually insert a row, or a couple of rows in the table, just to check, and yes, the trigger fires as well, when there is a proper insert. But I cannot explain why I keep receiving the e-mails!. As for the table itself, it's got nothing fancy.
USE [didaprod]
GO
/****** Object: Table [dbo].[Caseplayer_CaseId_Restore] Script Date: 09-08-2016 12:04:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Caseplayer_CaseId_Restore](
[Id] [int] NOT NULL,
[CaseId] [int] NOT NULL,
[TimeOfChange] [datetime] NOT NULL
) ON [PRIMARY]
GO
I've disabled the trigger now, and confirmed that the e-mails have stopped. But this seems like an almost magic problem for me, and I would love to get an answer.
Suppose I do
delete from [Caseplayer_CaseId_Restore]
And just leave the table alone.
I'll still get e-mails from the system, telling me to check the table. When I then perform a
select * from [Caseplayer_CaseId_Restore]
The table is empty
SQL Server triggers fire once per statement rather than once per row. That's why it's important to write triggers that use inserted appropriately, to deal with the fact that it may contain 1, many, or zero rows.
I suspect that it's the latter case here. (I.e. a regularly executed INSERT statement that is in fact inserting zero rows)
So, you might want something like:
CREATE trigger [dbo].[Caseplayer_CaseId_Restore_insert_mail]
on [dbo].[Caseplayer_CaseId_Restore]
AFTER INSERT
as
SET NOCOUNT ON
IF EXISTS(select * from inserted)
BEGIN
declare #tekst nvarchar(500);
set #tekst = 'caseid sat til null på caseplayer! Tjek Caseplayer_CaseId_Restore tabel!' + convert(varchar,getdate(),105);
EXEC msdb.dbo.sp_send_dbmail #profile_name = 'Mail',
#recipients = 'kk#byggeevaluering.dk',
#subject = 'CASEID SAT TIL NULL!!!',
#body = #tekst
END

Stored procedure insert two rows?

I have created a stored procedure using T-SQL.
I run it using this query
EXEC insertfbusers email, name
But when testing it in SQL Server Management Studio it inserts the same row twice, which causes a Primary Key violation.
The Primary Key is on the email column.
Why does it insert two rows?
Here's my procedure
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
-- ================================
-- Created
-- by: dbo
-- on: Monday, October 08, 2012 1:10 AM
-- Description: <Description>
-- ================================
ALTER PROCEDURE dbo.insertfbusers
-- Add the parameters for the procedure here
#email varchar(100),
#firstname varchar(50)
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO t_user VALUES (#email, #firstname)
END
I got it fixed! Must have been something wierd with the online based admin I used yesterday. I ran the code today from SQL MANAGEMENT STUDIO and it worked like a charm.
Thanks for the help anyway!

Resources