0

I am trying to get an efficient way of doing the stored procedure below. This procedure is to display a count of cars that belong to businesses in a market for all categories.

I have the category table being the primary select, then I go into the cars table to count the cars and join their businesses within the category and here is where it really gets inefficient I then check the market/locations selected or if none selected all markets. Here it is.

Create PROC  [USP_CAT]
  @MKT int

AS

BEGIN

    SELECT *,
      (
        SELECT COUNT(CAR_ID)
        FROM CARS
        INNER JOIN BUSINESS ON CAR_BIZ=BIZ_ID
        JOIN BIZCATS ON BC_BIZ = BIZ_ID AND BC_CAT = CAT_ID 
        WHERE  BIZ_APPROVED = 1 AND BIZ_EXPIRES >= getDate()  AND 
        (
          SELECT COUNT(BLOC_MKT)
          FROM BIZLOCS
          WHERE BIZ_ID = BLOC_BIZ AND (BLOC_MKT = @MKT OR @MKT = -1)
        )>0
      ) AS CAT_CAR_COUNT
    FROM CATS
    WHERE CAT_HIDE = 0
    ORDER BY CAT_ORDER asc

END

Any suggestion to tidy this up is much appreciated.

1
  • 2
    You would get better results if you posted the DDL, some sample inserts...and youre desired results. Sep 10, 2014 at 12:58

1 Answer 1

0

I think an EXISTS (http://msdn.microsoft.com/en-us/library/ms188336.aspx) might help out.

Create PROC  [USP_CAT]
  @MKT int

AS

BEGIN

    SELECT *,
      (
        SELECT COUNT(CAR_ID)
        FROM CARS
        INNER JOIN BUSINESS ON CAR_BIZ=BIZ_ID
        JOIN BIZCATS ON BC_BIZ = BIZ_ID AND BC_CAT = CAT_ID 
        WHERE  BIZ_APPROVED = 1 AND BIZ_EXPIRES >= getDate()  AND EXISTS
        (
          SELECT BLOC_MKT
          FROM BIZLOCS
          WHERE BIZ_ID = BLOC_BIZ AND (BLOC_MKT = @MKT OR @MKT = -1)
        )
      ) AS CAT_CAR_COUNT
    FROM CATS
    WHERE CAT_HIDE = 0
    ORDER BY CAT_ORDER asc

END
1
  • Thanks Drew, this is indeed an improvement; I will go with it. Just a side note, this is not a big part of the project on a whole, so if it affects performance when we are done, I will go with a no count option and just display categories. Sep 10, 2014 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.