I have one very simple function to do a sum based on the give year, month and part.
CREATE FUNCTION [dbo].[GetOpenOrders]
(@Part PartType,
@Month int,
@Year int)
RETURNS DECIMAL(19,8)
AS
BEGIN
DECLARE @OpenOrders int
SELECT @OpenOrders = SUM(CASE WHEN (QtyReturned <> 0 AND QtyShipped = 0) THEN (QtyOrdered - QtyShipped) ELSE (QtyOrdered - QtyShipped+ QtyReturned) END)
FROM CustomerOrder
LEFT JOIN CustomerOrderItem ON CustomerOrder.CustomerOrderNum = CustomerOrderItem.CustomerOrderNum
WHERE Part = @Part
AND MONTH(ISNULL(ISNUL(CustomerOrderItem.DueDate, CustomerOrderItem.PromiseDate), CustomerOrder.OrderDate)) = @Month
AND YEAR(ISNULL(ISNULL(CustomerOrderItem.DueDate, CustomerOrderItem.PromiseDate), CustomerOrder.OrderDate)) = @Year
AND CHARINDEX(CustomerOrder.Status, ' O ') > 0
AND CHARINDEX(CustomerOrderItem.stat, ' O') <> 0
RETURN ISNULL(@OpenOrders, 0)
END
There are 200000 rows for customer orders, and 400000 rows for Customer order items.
We noticed the issue yesterday, the function is taking 300ms to completed, with parameters (not specific value, just regular part, Year and Month).
The index on the CustomerOrder and CustomerOrderItem has been created.
Not sure what is going on.
But drop the function and recreate it fix the issue. The execution time drop to 4-5ms.
Want to understand what is cause of it. Since we didn't do any change to this function since 2020
Thank you in advance