Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Sproc Causing Timeout

Author  Topic 

Looper
Yak Posting Veteran

68 Posts

Posted - 2008-08-14 : 04:55:54
I am using the following stored procedure to do a search on a non unique field in a table that has 250000 rows. This is timing out and I wondered if anyone could see why or had any suggestions on writing a more effective procedure. The procedure includes a function call which I have also include.

thanks



CREATE PROCEDURE [dbo].[usp_SearchResults_ByNINumber]
(
@NINo varchar(8),
@UserId int
)
AS


-- Employees
SELECT DISTINCT empe.Surname + ', ' + empe.Forename AS [Name],
ISNULL(empe.Known, '') As KnownAs,
empe.NhssNo As NhssNo,
empe.DOB As DoB

FROM Main.dbo.t_Empmt empt
INNER JOIN Main.dbo.t_Empee empe ON empt.EmpeeId = empe.[Id]
INNER JOIN Work.dbo.t_ESW esw ON esw.EmpmtId = empt.Id

WHERE (SUBSTRING(empe.NINo,0,9) = @NINo) AND (dbo.UserHasCoveringRole(empt.Id,@UserId, 6) = 1 or
dbo.UserHasCoveringRole(empt.Id,@UserId, 7) = 1)


BEGIN
Declare @CompareDate datetime
SET @CompareDate = GETDATE()

-- Related Employments
SELECT DISTINCT ou.[Name] AS Employer,
emp.PayNo AS PayNo,
esp.FullScale As StaffCategory,
emp.StartDate As Status,
ee.NhssNo As EmpNhssNo,
esw.EmperId, esw.DivId, esw.DirId, esw.DepId, esw.SubId, esp.Full, CONVERT(VARCHAR(10),emp.StartDate,103) As StartDate,emp.StartDate As 'td'

FROM Main.dbo.t_Empmt emp
INNER JOIN Main.dbo.t_Empee ee ON emp.EmpeeId = ee.[Id]
INNER JOIN Main.dbo.t_OrgUnit ou ON emp.EmperId = ou.[Id]
INNER JOIN Work.dbo.t_ESW esw ON esw.EmpmtId = emp.Id
INNER JOIN Main.dbo.t_ESP esp ON emp.[Id] = esp.EmpmtId

WHERE (SUBSTRING(ee.NINo,0,9) = @NINo) AND (dbo.UserHasCoveringRole(emp.Id,@UserId, 6) = 1 or
dbo.UserHasCoveringRole(emp.Id,@UserId, 7) = 1)
ORDER BY emp.StartDate ASC
END



Create FUNCTION [dbo].[UserHasCoveringRole]
(@EmpmtId int, @UserId int, @RId int)
RETURNS int
AS
BEGIN
IF EXISTS(SELECT esw.ID
FROM dbo.t_ESW esw, dbo.t_UR ur
WHERE
ur.UId = @UId AND
ur.RId = @RId AND
esw.EmpmtId = @EmpmtId AND
(
(esw.EmperId = ur.EmployerId AND ur.DivisionChpId IS NULL) OR
(esw.DivId = ur.DivId AND ur.DirId IS NULL)OR
(esw.DirId = ur.DirId AND ur.DepId IS NULL)OR
(esw.DepId = ur.DepId AND ur.SubId IS NULL)OR
esw.SubId = ur.SubId
))
BEGIN
RETURN 1
END
RETURN 0
END

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-09-03 : 06:10:38
Replace the Function which have a massive cross join (cartesian product).
Make a table instead and maintain that table with trigger(s) on source table(s). Add proper indexes.

That massive cross join is executed for every row in the two queries in the sp.



E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page
   

- Advertisement -