I created a constraint that prevents allocations in one table to exceed inventory in another table (see the details in my previous question). But for some reason the constraint works as expected only when I insert new allocations, but on update it does not prevent violating.
Here is my constraint:
([dbo].[fn_AllocationIsValid]([Itemid]) = 1)
And here is the function:
CREATE FUNCTION [dbo].[fn_AllocationIsValid] (@itemId as int)
RETURNS int AS
BEGIN
DECLARE @isValid bit;
SELECT @isValid = CASE WHEN ISNULL(SUM(Allocation), 0) <= MAX(Inventory) THEN 1 ELSE 0 END
FROM Allocations A
JOIN Items I ON I.Id = A.ItemId
WHERE I.Id = @itemId
GROUP BY I.Id;
RETURN @isValid;
END
Updated
Here are my tables:
CREATE TABLE [allocations] (
[userID] [bigint] NOT NULL ,
[itemID] [int] NOT NULL ,
[allocation] [bigint] NOT NULL ,
CONSTRAINT [PK_allocations] PRIMARY KEY CLUSTERED
(
[userID],
[itemID]
) ON [PRIMARY] ,
CONSTRAINT [FK_allocations_items] FOREIGN KEY
(
[itemID]
) REFERENCES [items] (
[id]
) ON DELETE CASCADE ON UPDATE CASCADE ,
CONSTRAINT [CK_allocations] CHECK ([dbo].[fn_AllocationIsValid]([Itemid], [Allocation]) = 1)
) ON [PRIMARY]
CREATE TABLE [dbo].[Items](
[Id] [int] NOT NULL,
[Inventory] [int] NOT NULL
) ON [PRIMARY]
GO
INSERT INTO Items (Id, Inventory) VALUES (2692, 336)
INSERT INTO Allocations (UserId, ItemId, Allocation) VALUES(4340, 2692, 336)
INSERT INTO Allocations (UserId, ItemId, Allocation) VALUES(5895, 2692, 0)
The following statement execution should fail, but it does not:
update allocations set allocation = 5
where userid = 5895 and itemid = 2692