In the Range Checks over Multiple Rows section there is an example with 2 tables Accounting.Account and Accounting.AccountActivity using trigger to prevent activities that would cause negative balance of the individual accounts. It seems to mee (and not only in this case) that there is a double check if there exist inserted rows. The First is the statement “ IF @rowsAffected = 0 RETURN;” and the second in the validation section:
WHERE EXISTS (SELECT *
FROM inserted
WHERE inserted.AccountNumber =
AccountActivity.AccountNumber)
I have commented that EXISTS (see below) and it works OK. What is the reason of this second check. I cannot imagine situation where it would be necessary.
Follows the part of the Trigger ( with commented EXISTS under LEFT OUT AND WORKING ):
CREATE TRIGGER Accounting.AccountActivity$InsertTrigger
ON Accounting.AccountActivity
AFTER INSERT AS
BEGIN
SET NOCOUNT ON;
SET ROWCOUNT 0; --in case the client has modified the rowcount
--use inserted for insert or update trigger, deleted for update
--or delete trigger count instead of @rowcount due to merge behavior
-- that sets @rowcount to a number that is equal to number of merged
-- rows, not rows being checked in trigger
DECLARE @msg varchar(2000), --used to hold the error message
--use inserted for insert or update trigger, deleted for update
--or delete trigger count instead of @rowcount due to merge behavior
--that sets @rowcount to a number that is equal to number of merged
--rows, not rows being checked in trigger
@rowsAffected int = (SELECT COUNT(*) FROM inserted);
--no need to continue on if no rows affected
IF @rowsAffected = 0 RETURN;
BEGIN TRY
--[validation section]
--disallow Transactions that would put balance into negatives
IF EXISTS ( SELECT AccountNumber
FROM Accounting.AccountActivity AS AccountActivity
--LEFT OUT AND WORKING
--WHERE EXISTS (SELECT *
-- FROM inserted
-- WHERE inserted.AccountNumber =
-- AccountActivity.AccountNumber)
GROUP BY AccountNumber
HAVING SUM(Amount) < 0)