I have a table (Resources with about 18000 records) and a Table-Value Function with this body :
ALTER FUNCTION [dbo].[tfn_GetPackageResources]
(
@packageId int=null,
@resourceTypeId int=null,
@resourceCategoryId int=null,
@resourceGroupId int=null,
@resourceSubGroupId int=null
)
RETURNS TABLE
AS
RETURN
(
SELECT Resources.*
FROM Resources
INNER JOIN ResourceSubGroups ON Resources.ResourceSubGroupId=ResourceSubGroups.Id
INNER JOIN ResourceGroups ON ResourceSubGroups.ResourceGroupId=ResourceGroups.Id
INNER JOIN ResourceCategories ON ResourceGroups.ResourceCategoryId=ResourceCategories.Id
INNER JOIN ResourceTypes ON ResourceCategories.ResourceTypeId=ResourceTypes.Id
WHERE
(@resourceSubGroupId IS NULL OR ResourceSubGroupId=@resourceSubGroupId) AND
(@resourceGroupId IS NULL OR ResourceGroupId=@resourceGroupId) AND
(@resourceCategoryId IS NULL OR ResourceCategoryId=@resourceCategoryId) AND
(@resourceTypeId IS NULL OR ResourceTypeId=@resourceTypeId) AND
(@packageId IS NULL OR PackageId=@packageId)
)
now I make a query like this :
SELECT id
FROM dbo.tfn_GetPackageResources(@sourcePackageId,null,null,null,null)
WHERE id not in(
SELECT a.Id
FROM dbo.tfn_GetPackageResources(@sourcePackageId,null,null,null,null) a INNER JOIN
dbo.tfn_GetPackageResources(@comparePackageId,null,null,null,null) b
ON a.No = b.No AND
a.UnitCode=b.UnitCode AND
a.IsCompound=b.IsCompound AND
a.Title=b.Title
)
This query takes about 10 seconds!(Although each part query runs extremely fast but the whole one take time) I check it with LEFT JOIN
and NOT EXISTS
but the result was same.
but if I run the query on the Resources table directly it only takes one second or less! the fast query is :
select * from resources where id not in (select id from resources)
how can I solve it?