So, i have 2 tables:
Categories table
Analit int
PositionInMenu int
Item table
Analit int
CategoryAn int
So, i have about 50 categories and 2000 items. I need to take for each category count of items it includes.
1)SELECT *, (SELECT COUNT(Analit) FROM Item_table t2 WHERE t2.CategoryAn = t1.Analit) as tCount FROM Categories_table t1 ORDER BY PositionInMenu
2) Add into Categories table computed column with function call:
([dbo].[Categories_GetItemsCountInCategory]([Analit]))
and function code:
CREATE FUNCTION dbo.Categories_GetItemsCountInCategory
(
@categoryId int = null
)
RETURNS int
AS
BEGIN
RETURN (SELECT COUNT(Analit)
FROM Items
WHERE CategoryAn = @categoryId)
END
And then i can simply take value of added column into my query:
SELECT *
FROM Categories_table
ORDER BY PositionInMenu
So, the question. What’s better for me?
You are pretty much always better off having data access inline in the query rather than in scalar UDFs.
The query optimiser does not expand out scalar (or multi statement) UDFs so you always enforce a nested loops join plan rather than allowing it to consider alternatives.
You could also consider an
OUTER JOIN ... GROUP BYrather than a correlated subquery.