Solved

MSSQL/TSQL Stored Procedure needs optimization, any ideas?

Posted on 2004-10-06
8
326 Views
Last Modified: 2006-11-17
I'm looking for some pointers here on how to optimize this stored procedure and how to measure it's performance. This is going to be used on a site that supports multiple languages.
It involves two tables. Genres and GenresText. GenresText is a table with all the localized strings in it with a GenreID in it referring back to Genres.

If all text was populated a normal query would be:
SELECT *
FROM Genres,GenresText
WHERE Genres.GenreID = GenresText.GenreID
 AND GenresText.LocaleID = @localeID
 AND Genres.StatusID = 1
 AND GenresText.StatusID = 1

But that's not the case, I've created a fallback algorithm that will look for text from the preferred locale and if that doesn't exist then get it from the fallback locale. That algorithm is implemented in the stored procedure you will find below.

Genres Table:
CREATE TABLE [dbo].[Genres] ( [GenreID] [int] IDENTITY (1, 1) NOT NULL , [StatusID] [int] NOT NULL ) ON [PRIMARY]
ALTER TABLE [dbo].[Genres] WITH NOCHECK ADD  CONSTRAINT [PK_Genres] PRIMARY KEY  CLUSTERED ( [GenreID] )  ON [PRIMARY]

GenresText Table:
CREATE TABLE [dbo].[GenresText] (
      [GenreTextID] [int] IDENTITY (1, 1) NOT NULL ,
      [GenreID] [int] NOT NULL ,
      [LocaleID] [int] NOT NULL ,
      [Title] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [StatusID] [int] NOT NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[GenresText] WITH NOCHECK ADD CONSTRAINT [PK_GenresText] PRIMARY KEY  CLUSTERED ([GenreTextID])  ON [PRIMARY]

GetArtistGenres Stored Procedure:
ALTER PROCEDURE getArtistGenres
@localeID int,
@fallBackLocaleID int,
@showStaging int
AS

SET NOCOUNT ON

CREATE TABLE #tempGenres (GID INT, Title VARCHAR(255))

DECLARE @title VARCHAR(255)
DECLARE @productStatus VARCHAR(255)
 
 
INSERT #tempGenres (GID)
SELECT GenreID FROM Genres

DECLARE genres_cursor INSENSITIVE CURSOR
FOR
      SELECT GID FROM #tempGenres

OPEN genres_cursor
DECLARE @tgid int
FETCH genres_cursor INTO @tgid

WHILE @@FETCH_STATUS = 0
BEGIN
      IF EXISTS (SELECT Title FROM GenresText,Genres WHERE Genres.GenreID = GenresText.GenreID AND GenresText.LocaleID in (@localeID,@fallbackLocaleID) AND GenresText.GenreID=@tgid)
      BEGIN
            IF @showStaging = 1
                  BEGIN
                        SELECT @title = GenresText.Title
                        FROM GenresText INNER JOIN
                              Genres ON GenresText.GenreID = Genres.GenreID
                        WHERE (GenresText.LocaleID = @localeID)
                              AND (GenresText.GenreID = @tgid)
                              AND (Genres.StatusID = 1)
                              AND (GenresText.StatusID = 1)
                  END
            ELSE
                  BEGIN
                        SELECT @title = GenresText.Title
                        FROM GenresText INNER JOIN
                              Genres ON GenresText.GenreID = Genres.GenreID
                        WHERE (GenresText.LocaleID = @localeID)
                              AND (GenresText.GenreID = @tgid)
                              AND (Genres.StatusID in (1,2))
                              AND (GenresText.StatusID in (1,2))
                  END
            END
      ELSE
            IF @showStaging = 1
                  BEGIN
                        SELECT @title = GenresText.Title
                        FROM GenresText INNER JOIN
                              Genres ON GenresText.GenreID = Genres.GenreID
                        WHERE (GenresText.LocaleID = @fallBackLocaleID)
                              AND (GenresText.GenreID = @tgid)
                              AND (Genres.StatusID = 1)
                              AND (GenresText.StatusID = 1)
                  END
            ELSE
                        SELECT @title = GenresText.Title
                        FROM GenresText INNER JOIN
                              Genres ON GenresText.GenreID = Genres.GenreID
                        WHERE (GenresText.LocaleID = @fallBackLocaleID)
                              AND (GenresText.GenreID = @tgid)
                              AND (Genres.StatusID in (1,2))
                              AND (GenresText.StatusID in (1,2))
            
            UPDATE #tempGenres
                  SET title = @title
            WHERE GID=@tgid
            
      FETCH genres_cursor INTO @tgid
END

SET NOCOUNT OFF

SELECT GID,Title
FROM #tempGenres
ORDER BY Title

-- # LEAVE AT END #
DROP TABLE #tempGenres  
CLOSE genres_cursor  
DEALLOCATE genres_cursor
-- # LEAVE AT END #



0
Comment
Question by:jbrahy
  • 4
  • 4
8 Comments
 
LVL 7

Accepted Solution

by:
Nievergelt earned 250 total points
ID: 12241843
If you are looking to boost performance:
- Do not use cursors. They are notoriously slow as they do not allow the database engine do help make things faster.
- Try to use joins (even outer joins), the COALESCE function and maybe also CASE clauses.

Try something like this:

SELECT COALESCE (loc.title, altLoc.title) AS title
FROM Genres g INNER JOIN GenresText altLoc ON g.genreId = altLoc.genreId AND altLoc.localeId = 1
                       LEFT OUTER JOIN GenresText loc ON altLoc.genreId = loc.genreId AND loc.localeId = 2
0
 
LVL 1

Author Comment

by:jbrahy
ID: 12242034
damn, that's good.

I've never used COALESCE before, I really like it now.

SELECT COALESCE (loc.title, altLoc.title) AS title
FROM Genres
        LEFT OUTER JOIN GenresText loc
            ON Genres.GenreID = loc.GenreID
                  AND loc.LocaleID= 2
      INNER JOIN GenresText altLoc
            ON Genres.GenreID = altLoc.GenreID
                  AND altLoc.LocaleID = 1

I usually do my joins without the JOIN keywords, can this be done in that fashion?
something like this?

SELECT COALESCE (loc.title, altLoc.title) AS title
FROM Genres, GenresText loc altloc
WHERE Genres.GenreID = loc.GenreID AND loc.LocaleID= 2
  AND Genres.GenreID = altLoc.GenreID AND altLoc.LocaleID = 1





0
 
LVL 7

Expert Comment

by:Nievergelt
ID: 12242207
If you do not use the JOIN syntax, I think you can only do inner joins.
But what you want to do is to have an outer join, i.e. a join where the columns of the missing table row are filled with "virtual" NULL values to be able to recognize the missing values.
Instead of COALESCE (that works also for multiple values) the same result could also be achieved with an appropriate CASE WHEN ... IS NULL ...
0
 
LVL 1

Author Comment

by:jbrahy
ID: 12242334
Which is more efficent? and how do I check the process utilization?
0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
LVL 7

Expert Comment

by:Nievergelt
ID: 12242402
I do not assume that you will see performance differences; it is just a matter of style.
0
 
LVL 1

Author Comment

by:jbrahy
ID: 12242495
The original question had two parts, what is a way to optimize the code and how can I measure the optimizations. Do you have an answer to that half of the question?

Thanks,

John
0
 
LVL 7

Expert Comment

by:Nievergelt
ID: 12242642
Sorry John,

I do not know how to measure perfomance with SQL Server.

Maybe you start a new question?

Cheers  Christoph
0
 
LVL 1

Author Comment

by:jbrahy
ID: 12242717
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Introduction: Often, when running a query with joins, the results show up "duplicates", and often, those duplicates can be "eliminated" in the results using DISTINCT, for example. Using DISTINCT is simple: just add it after the SELECT keyword, an…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now