I am new to a particular job and using Scalar Functions for the first time.
The more records I try to process however the S L O W E R .. it gets..
Am I doing something wrong? I am reading from a view and have 2 criteria in the WHERE clause.
40 records or even 400 returns fairly fast.. (this is an old spaghetti app btw running on SQL Server 2008) but start trying to crunch 800+ records and it gets exponentially slower..
Any suggestions?
ALTER FUNCTION [dbo].[GetAccount_Total_By_Domain]
(@domain nvarchar(128), @status nvarchar(128))
RETURNS decimal(10, 2)
AS
BEGIN
DECLARE @allAccountsTotal int;
DECLARE @statusTotal int;
DECLARE @returnPercent decimal(10,2);
SELECT
@allAccountsTotal = COUNT(*)
FROM [NDCSTATS].[dbo].[SEC_ADMIN_ACCOUNT_COMPLIANCE_VW]
WHERE Domain = @domain;
SELECT
@statusTotal = COUNT(*)
FROM [NDCSTATS].[dbo].[SEC_ADMIN_ACCOUNT_COMPLIANCE_VW]
WHERE Domain = @domain AND StatusVal = @status;
SET @returnPercent = CAST(100 * SUM(@statusTotal) / SUM(@allAccountsTotal) OVER() AS DECIMAL(10, 2))
--100 * @allAccountsTotal / @statusTotal;
RETURN @returnPercent;
END
UPDATE:
I have put a nonclustered index on the Core
table which in this case is DOMAIN
an nvarchar(128)
type value since we are grouping by Domain - but also StatusVal - only StatusVal is not available until the View where we do a UNION.
I also removed columns not needed in the Core table and the queries have sped a bit until up around 2000 records.. but still having trouble with the big ones like 10k records.
I also added some criteria columns to the INDEX that are BIT columns so they are fast I hope!!