Solved

SQL Delete Trigger works for single row delete only

Posted on 2011-09-19
11
308 Views
Last Modified: 2012-05-12
This SP works for a single row operation only... Any ideas?

IF EXISTS (SELECT 1 FROM sysobjects WHERE name = 'AuthCodeToDeviceSettings3' AND type = 'TR')
DROP TRIGGER  AuthCodeToDeviceSettings3
GO
CREATE TRIGGER AuthCodeToDeviceSettings3 ON [AuthCodes]
FOR DELETE
AS

DECLARE @AuthCodesID As INT
DECLARE @DeviceID As INT
DECLARE @DatabaseValue As INT
SELECT @AuthCodesID = (SELECT AuthCodesID FROM Deleted)
SELECT @DeviceID = (SELECT DeviceID FROM  Deleted WHERE [AuthCodesID] = @AuthCodesID)
SELECT @DatabaseValue = (SELECT [DatabaseValue] FROM [DeviceSettings] WHERE [DeviceID] = @DeviceID AND [ItemName] = '!TabUser' AND [DatabaseValue] > 0 )


BEGIN
UPDATE [dbo].[DeviceSettings]
     SET
                  [DatabaseValue] = (@DatabaseValue + 1)
     WHERE
                  [DeviceID] = @DeviceID AND [ItemName] = '!TabUser' AND [DatabaseValue] > 0        
IF @@ROWCOUNT=0
    UPDATE [dbo].[DeviceSettings]
     SET
                  [DatabaseValue] = 1
     WHERE
                  [DeviceID] = @DeviceID AND [ItemName] = '!TabUser'
END
GO
0
Comment
Question by:MBoy
  • 6
  • 3
  • 2
11 Comments
 
LVL 39

Expert Comment

by:Pratima Pharande
Comment Utility
try this

IF EXISTS (SELECT 1 FROM sysobjects WHERE name = 'AuthCodeToDeviceSettings3' AND type = 'TR')
DROP TRIGGER  AuthCodeToDeviceSettings3
GO
CREATE TRIGGER AuthCodeToDeviceSettings3 ON [AuthCodes]
FOR DELETE
AS

BEGIN
UPDATE [dbo].[DeviceSettings]
     SET
                  [DatabaseValue] = [DatabaseValue] + 1
     WHERE
                  [DeviceID] in

 (SELECT DeviceID FROM  Deleted )

AND [ItemName] = '!TabUser' AND [DatabaseValue] > 0        


IF @@ROWCOUNT=0
    UPDATE [dbo].[DeviceSettings]
     SET
                  [DatabaseValue] = 1
     WHERE
                  [DeviceID] in

 (SELECT DeviceID FROM  Deleted ) AND [ItemName] = '!TabUser'
END
GO
0
 
LVL 39

Expert Comment

by:Pratima Pharande
Comment Utility
your code is not working for all records b'coz

SELECT @AuthCodesID = (SELECT AuthCodesID FROM Deleted)
SELECT @DeviceID = (SELECT DeviceID FROM  Deleted WHERE [AuthCodesID] = @AuthCodesID)
SELECT @DatabaseValue = (SELECT [DatabaseValue] FROM [DeviceSettings] WHERE [DeviceID] = @DeviceID AND [ItemName] = '!TabUser' AND [DatabaseValue] > 0 )

this will gives you only first record from deleted

when multiple records are deleted will come all together is deleted table
0
 
LVL 8

Expert Comment

by:raulggonzalez
Comment Utility
Hi, your problem is how you use DELETED table

when you do

SELECT @AuthCodesID = (SELECT AuthCodesID FROM Deleted)

you can only keep one value in @AuthCodesID because is just a variable, so you execute the update just for one value...

You have to look for the way of looping through DELETED table to use all the values in there.

0
 
LVL 8

Expert Comment

by:raulggonzalez
Comment Utility
Please try something like this

IF EXISTS (SELECT 1 FROM sysobjects WHERE name = 'AuthCodeToDeviceSettings3' AND type = 'TR')
DROP TRIGGER  AuthCodeToDeviceSettings3
GO
CREATE TRIGGER AuthCodeToDeviceSettings3 ON [AuthCodes]
FOR DELETE
AS
BEGIN
      UPDATE [dbo].[DeviceSettings]
            SET [DatabaseValue] = ISNULL([DatabaseValue], 0)
            WHERE [DeviceID] = (SELECT DeviceID
                                                FROM  Deleted
                                                WHERE [AuthCodesID] = (SELECT AuthCodesID FROM Deleted))
                  AND [ItemName] = '!TabUser' AND [DatabaseValue] > 0        

GO
0
 
LVL 8

Expert Comment

by:raulggonzalez
Comment Utility
Sorry, last condition is no needed

IF EXISTS (SELECT 1 FROM sysobjects WHERE name = 'AuthCodeToDeviceSettings3' AND type = 'TR')
DROP TRIGGER  AuthCodeToDeviceSettings3
GO
CREATE TRIGGER AuthCodeToDeviceSettings3 ON [AuthCodes]
FOR DELETE
AS
BEGIN
      UPDATE [dbo].[DeviceSettings]
            SET [DatabaseValue] = ISNULL([DatabaseValue], 0)
            WHERE [DeviceID] = (SELECT DeviceID
                                                FROM  Deleted
                                                WHERE [AuthCodesID] = (SELECT AuthCodesID FROM Deleted))
                  AND [ItemName] = '!TabUser'

GO
0
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 
LVL 8

Expert Comment

by:raulggonzalez
Comment Utility
Again... this should be the final :)


IF EXISTS (SELECT 1 FROM sysobjects WHERE name = 'AuthCodeToDeviceSettings3' AND type = 'TR')
DROP TRIGGER  AuthCodeToDeviceSettings3
GO
CREATE TRIGGER AuthCodeToDeviceSettings3 ON [AuthCodes]
FOR DELETE
AS
BEGIN
	UPDATE [dbo].[DeviceSettings]
		SET [DatabaseValue] = ISNULL([DatabaseValue], 0) + 1
		WHERE [DeviceID] = (SELECT DeviceID 
								FROM  Deleted 
								WHERE [AuthCodesID] = (SELECT AuthCodesID FROM Deleted)) 
			AND [ItemName] = '!TabUser'

GO

Open in new window

0
 
LVL 39

Accepted Solution

by:
Pratima Pharande earned 500 total points
Comment Utility
IF EXISTS (SELECT 1 FROM sysobjects WHERE name = 'AuthCodeToDeviceSettings3' AND type = 'TR')
DROP TRIGGER  AuthCodeToDeviceSettings3
GO
CREATE TRIGGER AuthCodeToDeviceSettings3 ON [AuthCodes]
FOR DELETE
AS

BEGIN
UPDATE DV
     SET
                  DV.[DatabaseValue] = DV.[DatabaseValue] + 1

From [dbo].[DeviceSettings] DV
Inner join Deleted D on DV.[DeviceID] = D.[DeviceID]
     WHERE
                 AND DV.[ItemName] = '!TabUser' AND DV.[DatabaseValue] > 0        


IF @@ROWCOUNT=0
    UPDATE DV
     SET
                  DV.[DatabaseValue] = 1

From [dbo].[DeviceSettings] DV
Inner join Deleted D on DV.[DeviceID] = D.[DeviceID]
     WHERE
                 AND DV.[ItemName] = '!TabUser' AND DV.[DatabaseValue] > 0        

END
GO
0
 
LVL 8

Expert Comment

by:raulggonzalez
Comment Utility
Hi, I couldn't test my solution  (obviously) but I really think that there's no need to have 2 different UPDATES.

The first UPDATE just differs from the second on the condition (DatabaseValue > 0), so I assumed that was because maybe DatabaseValue can be NULL, so NULL + 1 = NULL... that's why I put ISNULL(), to avoid it.

Probably #pratima_mcs' idea about the JOIN is fine but should work the same like the subqueries.

Hope you can make it.

cheers
0
 
LVL 3

Author Comment

by:MBoy
Comment Utility
I'm on Asian time but I will check these tomorrow morning - Thanks
0
 
LVL 3

Author Closing Comment

by:MBoy
Comment Utility
Thanks
0
 
LVL 8

Expert Comment

by:raulggonzalez
Comment Utility
Hi,

I think I'm not wrong if I say that the solution you accepted is buggy, because both UPDATE have exactly the same WHERE clause. (Apart from the syntax error)

1st update

     WHERE -- missing condition
                 AND DV.[ItemName] = '!TabUser' AND DV.[DatabaseValue] > 0  

2nd update
WHERE -- missing condition
                 AND DV.[ItemName] = '!TabUser' AND DV.[DatabaseValue] > 0 -- same condition as the first so same set of rows will be affected (zero)


So if you execute the first UPDATE and @@ROWCOUNT = 0 then you execute the second UPDATE which will affect the same set of records, so ZERO records will be updated.

Please review it.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Select2 jquery help 9 41
Full Text Search string 5 32
MS SQL 2016 from Database to Datawarehouse 6 34
SQL Maintenance Plan 3 13
SQL Server engine let you use a Windows account or a SQL Server account to connect to a SQL Server instance. This can be configured immediatly during the SQL Server installation or after in the Server Authentication section in the Server properties …
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now