SQL Trigger not updating all inserted rows - sql-server

SQL Trigger is not updating all the inserted rows, only few rows get updated,I am not able to understand why. The rows are are getting row ID and RateID, I have tested the trigger by making rowId entries in the Audit log
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[mytrigger]
ON [dbo].[myTable]
AFTER INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #RowId int,
#RateID int,
#RateCode NVARCHAR(50)
SELECT #RateID = RateID,
#RowId = RowId
FROM inserted
// Method I found on StackOverflow
-- Update cr
-- Set cr.RateCode = r.RateCode
-- From mytable cr
-- inner join inserted on cr.RowId = inserted.RowId
-- inner join rates r on inserted.RateID = r.ID
--where cr.RowId = inserted.RowId
//Method Aaron Suggested
--UPDATE t1
--SET t1.RateCode = t2.RateCode
--FROM dbo.mytable AS t1
-- INNER JOIN dbo.rates AS t2
-- ON t1.RateID = t2.ID
-- WHERE t1.RowId = inserted.RowId
// Method I am currently using
IF #RateID IS NOT NULL
BEGIN
Select #RateCode = RateCode From rates where ID = #RateID
IF #RateCode IS NOT NULL
Update mytable Set RateCode = #RateCode Where RowId = #RowId
--UPDATE [dbo].[mytable ] SET RateCode = #RateCode FROM Inserted i WHERE mytable .RowId = i.RowId
END
END

Related

SQL Server trigger only if a field is false prior to update

I have written the trigger below that inserts values if the emailstudio column is updated. This column can be 0 or 1.
How can I write the trigger so that it only fires if the emailstudio column is changed from 0 to 1, not if it was already 1?
Thank you
ALTER TRIGGER [dbo].[RM_Est_Email_Trigger]
ON [dbo].[K3_BriefHeader]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #estimate int, #Email_Date datetime, #status int, #emailstudio bit
SET #estimate = (SELECT Estimate from inserted)
set #Email_Date = GETDATE()
SET #status = (SELECT Status from inserted)
SET #emailstudio = (SELECT EmailStudio from inserted)
IF UPDATE (EmailStudio)
BEGIN
INSERT INTO [dbo].[K3_EstimateEmailDate] ([Estimate], [Email_Date],[Status], [EmailStudio])
VALUES (#estimate, #Email_Date, #status, #emailstudio)
END
END
Insert INTO [dbo].[K3_EstimateEmailDate] (
[Estimate]
,[Email_Date]
,[Status]
,[EmailStudio]
)
SELECT Estimate
,GETDATE()
,status
,1
FROM inserted
LEFT JOIN deleted
ON deleted.<primarykey> = inserted.<primarykey>
WHERE inserted.emailstudio = 1
AND (deleted.emailstudio is null -- inserted
OR deleted.emailstudio = 0) -- updated

SQL Server create Triggers on INSERT and SELECT OUTCOME

I try to create a Trigger that will insert a Unique ID in a table and then get the created ID and use it on the table that "Triggered the trigger"
So I insert some data in my table and then I want the trigger to insert some data in another table (master ID table), it then needs to get the just created ID (auto increment INT) and add this ID to the table ID that the trigger fired on.
I tried quite some different options but it just does not insert the ID and it will give me an error.
Hope you can help me out.
CREATE TRIGGER [dbo].[TROidMemoDiaryHeader]
ON [dbo].[InvoiceDiaryHeader]
FOR INSERT
AS
DECLARE #TEMP uniqueidentifier, #Lock INT, #Object INT, #User V ARCHAR(MAX), #Delay NCHAR(12), #ID INT
SET #TEMP = NEWID()
SET #Lock = '0' --staat geen wijziging meer toe
SET #Object = '5' -- aanduiding bron
SET #User = CURRENT_USER
--SET #Delay = '00:00:00:125' -- Wacht voor een kwart seconde voor verder te gaan
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
--SET NOCOUNT ON;
INSERT INTO [dbo].[AbstractMBOBase] ([Uid], [OptimisticLockField], [ObjectType], [User])
SELECT #TEMP, #Lock, #Object, #User
IF EXISTS (SELECT [Uid] FROM [dbo].AbstractMBOBase WHERE [Uid] = #TEMP)
BEGIN
INSERT INTO [InvoiceDiaryHeader](Oid)
SELECT Oid FROM inserted
/*
SELECT * INTO #tmpOID FROM AbstractMBOBase WHERE [Uid] = #TEMP
UPDATE [dbo].InvoiceDiaryHeader SET Oid = (SELECT a.[Oid] FROM [dbo].[AbstractMBOBase] AS a
WHERE [Uid] = #TEMP)
--CREATE TABLE [dbo].#TempOID()
--SELECT * INTO #TempOID FROM INSERTED
*/
/*
--UPDATE [MemoDiaryHeader]
SET #ID = (SELECT a.[Oid] FROM [dbo].[AbstractMBOBase] AS a
WHERE [Uid] = #TEMP)
INSERT INTO [MemoDiaryHeader]([Oid])
SELECT #ID
--FROM inserted
--select [Oid]=i.[Oid] from inserted i
*/
END
--END
END
GO

Trouble with SQL trigger

Need help with a trigger.
If I remove my inner joins from where clause it runs, so I'm guessing this is where the issue would be. If I use this where clause it works "WHERE oeordhdr_sql.A4GLIdentity =#id "
Any help would be appreciated. Below is the code...
ALTER trigger [dbo].[bdordermakeonhold]
on [dbo].[oeordhdr_sql]
for insert
as
declare #edi as char(1)
declare #id as numeric(9,0)
declare #ordno as char(8)
declare #ordtype as char(1)
declare #cus_no as char(12)
declare #status as char(1)
declare #ship_to_addr_3 as char(40)
set #edi=(select edi_fg from inserted)
set #id=(select a4glidentity from inserted)
set #ordno=(select ord_no from inserted)
set #ordtype=(select ord_type from inserted)
set #cus_no=(select cus_no from inserted)
set #status=(select status from inserted)
set #ship_to_addr_3=(select status from inserted)
set nocount on
if #edi is null or #edi='E'
if not exists (SELECT ID, Cus_No, State, CertificateID, Expiration FROM BDSalesTaxCerts
WHERE State = 'FL' AND #cus_no = Cus_No)
begin
UPDATE oeordhdr_sql
SET status = 'C',hold_fg = 'H'
FROM inserted AS i INNER JOIN
oeordlin_sql AS LN ON LN.ord_no = i.ord_no INNER JOIN
ARCUSFIL_SQL as CS ON i.cus_no = CS.cus_no
WHERE oeordhdr_sql.A4GLIdentity =#id and cs.state not in ('FL','PR',' ','lima') and
(LN.loc = 'SE') AND (#ship_to_addr_3 LIKE '%FL%') AND #status in ('1')
if not exists (select ID from BDInvoiceSupport where Orig_Ord_no=#ordno and orig_ord_type
=#ordtype)
begin
INSERT INTO [dbo].[BDInvoiceSupport]
([ID]
,[LastUpdate]
,[RecordRevLevel]
,[Inv_No]
,[TaxProcessingStatus]
,[Orig_Ord_no]
,[orig_ord_type]
,[InvoiceSent]
,[OnHoldReason])
select NEWID(),GETDATE(),0,inv_no,0,ord_no,ord_type,0,'Not checked yet.'
from inserted
end
end
If two rows get inserted at once, this would give you problems. You should write it with joins to the inserted table, instead of using variables.

Update Trigger, set value for the inserted data SQL Server

I need to create a trigger, if update is assigning a user. And we have not set the value before.
I have this but server doesn't like it.... I get an error
Incorrect syntax near '.'
on the 'set' line.
CREATE TRIGGER dbo.trgIssueAcknowledged
ON dbo.hdIssues
AFTER UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
If (select inserted.AssignedToUserID from inserted) IS NULL
begin
return
end
If (select inserted.AssignedToUserID from inserted) = 0
begin
return
end
If (select inserted.AcknowledgeDate from inserted) IS NULL
begin
set inserted.AcknowledgeDate = GETDATE ( );
end
END
GO
Your trigger has many issues, it doesn't use the real table you want to update, it assumes only one row is modified every time, and the logic with the RETURN is too weird.
CREATE TRIGGER dbo.trgIssueAcknowledged
ON dbo.hdIssues
AFTER UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
UPDATE A
SET A.AcknowledgeDate = GETDATE()
FROM dbo.hdIssues A
INNER JOIN INSERTED I
ON A.TheKeyOfTheTable = I.TheKeyOfTheTable
WHERE A.AcknowledgeDate IS NULL
AND ( A.AssignedToUserID <> 0 AND A.AssignedToUserID IS NOT NULL)
END
Could it perhaps be the spelling mistake?
inserted.AcknoledgeDate
looks like it is missing "w"
should be
inserted.AcknowledgeDate
Try This
CREATE TRIGGER dbo.trgIssueAcknowledged ON dbo.hdIssues
AFTER INSERT, DELETE, UPDATE
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
DECLARE #INSERTCOUNT INT
DECLARE #DELETECOUNT INT
SET #INSERTCOUNT = ( SELECT COUNT(*)
FROM INSERTED
)
SET #DELETECOUNT = ( SELECT COUNT(*)
FROM DELETED
)
IF #INSERTCOUNT > 0
AND #DELETECOUNT = 0
BEGIN
-- Insert statements for trigger here
INSERT INTO dbo.hdIssues
( col1, col2)
SELECT I.col1,
I.col2
FROM INSERTED I
END
ELSE
IF #INSERTCOUNT > 0
AND #DELETECOUNT > 0
BEGIN
INSERT INTO dbo.hdIssues
( col1, col2)
SELECT I.col1,
I.col2
FROM INSERTED I
INNER JOIN DELETED D ON I.col1 = D.col1
WHERE I.col1 <> D.col1
OR
I.col2 <> D.col2
END
END TRY
BEGIN CATCH
END CATCH
END
GO
Well first of all inserted is a virtual table, so if you want to update one of the columns, you need to do an UPDATE.
UPDATE inserted
set AcknowledgeDate = GETDATE ( )
WHERE AcknowledgeDate IS NULL;
But second of all, why do you want to update the value in the inserted table in an AFTER UPDATE trigger? What are you really trying to do?

how to insert into table but only if the record doesnt exist

I've got a table that stores the following:
JobID
ValidationItemID
CreatedBy
I want to be able to insert into this table (a predefined template) but only add rows that dont exist. What I mean by dont exist is the combination of JobID and ValidationItemID make the row unique. My procedure passes in a JobID, but I cannot pass in a validation item ID as I pull this column as part of the template...
Something to this effect:
CREATE PROCEDURE insTemplate
#JobID varchar(50),
#Login varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO
ValidationItemSignOff
(
JobID,
ValidationItemID,
CreatedBy
)
SELECT
DISTINCT
#JobID,
vi.ValidationItemID,
#Login
FROM
RunOffAnswer roa
INNER JOIN
Method m ON m.MethodID = roa.MethodID
INNER JOIN
RunOffValidationItem vi ON vi.ValidationItemID = m.ValidationItemID
WHERE
vi.Inactive=0
AND NOT EXISTS(SELECT * FROM ValidationItemSignOff WHERE JobID=#JobID AND vi.ValidationItemID ???
END
GO
I dont know how to phrase the where condition so that it doesn't reinsert the same JobID and ValidationItemID. Lets say I have inside the table:
Job ValidationItem
Job A 1
Job A 2
Job A 5
And I have a template with the following:
ValidationItem
1
2
3
4
5
6
When I run my stored procedure it should only insert values 3,4,6 from the template table, for the job id... So I need help with my where condition.
I think my issue is I cannot use NOT EXISTS, maybe I need to join back to this ValidationItemSignOff table itself on JobID and ValidationItemID where ValidationItemID is NULL, maybe like this:
CREATE PROCEDURE insTemplate
#JobID varchar(50),
#Login varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO
ValidationItemSignOff
(
JobID,
ValidationItemID,
CreatedBy
)
SELECT
DISTINCT
#JobID,
vi.ValidationItemID,
#Login
FROM
RunOffAnswer roa
INNER JOIN
Method m ON m.MethodID = roa.MethodID
INNER JOIN
RunOffValidationItem vi ON vi.ValidationItemID = m.ValidationItemID
RIGHT OUTER JOIN
ValidationItemSignOff viso ON viso.JobID = #JobID
AND viso.ValidationItemID = vi.ValidationItemID
WHERE
vi.Inactive=0
AND viso.ValidationItemID IS NULL
END
GO
Got it I think
Replacing the right join with this:
LEFT JOIN
ValidationItemSignOff viso
ON viso.JobID = #JobID
AND viso.ValidationItemID = vi.ValidationItemID
If you're on 2008 or above...
MERGE INTO ValidationItemSignOff As Target
USING (SELECT DISTINCT #JobID, vi.ValidationItemID, #Login
FROM RunOffAnswer roa INNER JOIN
Method m
ON m.MethodID = roa.MethodID INNER JOIN
RunOffValidationItem vi
ON vi.ValidationItemID = m.ValidationItemID
WHERE vi.Inactive = 0) As Source (JobID, ValidationItemID, Login)
ON Target.JobID = Source.JobID
AND Target.ValidationItemID = Source.ValidationItemID
WHEN NOT MATCHED BY TARGET THEN
INSERT (JobID, ValidationItemID, CreatedBy)
VALUES (Source.JobID, Source.ValidationItemID, Source.Login);
Disclaimer: I may have not got the syntax spot on here.
I got it with this:
ALTER PROCEDURE insSignOffTemplate
#JobID varchar(50),
#Login varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO
ValidationItemSignOff
(
JobID,
ValidationItemID,
CreatedBy
)
SELECT
DISTINCT
#JobID,
vi.ValidationItemID,
#Login
FROM
RunOffAnswer roa
INNER JOIN
Method m
ON
m.MethodID = roa.MethodID
INNER JOIN
RunOffValidationItem vi
ON
vi.ValidationItemID = m.ValidationItemID
LEFT JOIN
ValidationItemSignOff viso
ON viso.JobID = #JobID AND viso.ValidationItemID = vi.ValidationItemID
WHERE
vi.Inactive=0
AND viso.ValidationItemID IS NULL
END
GO

Resources