I have created the following function in my database
Create FUNCTION [dbo].[CountUseer](@couponid INT)
RETURNS INT
AS
BEGIN
RETURN
(
SELECT Count(cu.id) NofUses --- this can only return one column
FROM Coupon as c
JOIN CouponUse as cu
ON c.id = cu.couponid
WHERE cu.couponid = @couponid
)
END
Then I run this query
ALTER TABLE dbo.Coupon
ADD NofUses AS dbo.CountUseer(Id)
Now when I try to create an index on the column NofUses :
CREATE INDEX Noofusesindex ON Coupon (NofUses)
I get this error:
Column ‘NofUses’ in table ‘Coupon’ cannot be used in an index or
statistics or as a partition key because it is non-deterministic.
Well, the error message really says it all: since this function is non-deterministic (e.g. when you call it with the same input parameters, there’s no guarantee you’ll get the same results every time), it cannot be indexed.
The only way around this would be to make it a regular column (not based on a function), and just update the value stored in that column on a regular basis (by a SQL Agent job, for instance, or by a trigger on the
CouponUsetable, or some other mechanism)