473,543 Members | 2,001 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Stored procedure performance optimization

Hello,

I have a question regarding stored procedure desing that provides the
optimal performance. Let's say we have a table Products that consists of
three columns: Name, Status, RegistrationTim e. All columns are indexed and
users should be able to lookup data by any of the columns. We have two main
options to design stored procedures for data retrieval:

1. Design separate stored procedures for each search criteria:
LookupProductsB yName, LookupProductsB yStatus, LookupProductsB yTime.

2. Write a generic stored procedure that will fit any search criteria:

CREATE PROCEDURE GetProducts (
@Name varchar(20),
@Status int = NULL,
@FromTime datetime = NULL,
@ToTime datetime = NULL)
AS BEGIN
SELECT
[Name],
[Status],
[RegistrationTim e]
FROM [Products]
WHERE [Name]=CASE
WHEN @Name<>NULL THEN @Name
ELSE [Name]
END
AND [Status]=CASE
WHEN @Status<>NULL THEN @Status
ELSE [Status]
END
AND [RegistrationTim e]>=CASE
WHEN @FromTimestamp< >NULL THEN @FromTimestamp
ELSE [RegistrationTim e]
END
AND [RegistrationTim e]<=CASE
WHEN @ToTimestamp<>N ULL THEN @ToTimestamp
ELSE [RegistrationTim e]
END
ORDER BY [RegistrationTim e]
END;

The second option is very attractive, because it is obviously easier to
maintain such code. However, I am a little concerned about performance of
such stored procedure. It is not possible to foresee what index should be
used, index can only be selected each during procedure execution, because
search criteria can include either Name, Status or RegistrationTim e. Will it
make this SP inefficient? Or perormance difference in such case is not big
(if any) and we should choose the second option because of its significant
code reduction?

Thanks in advance

Vagif Abilov
va***@online.no
Jul 20 '05 #1
3 4253

"Vagif Abilov" <va***@online.n o> wrote in message
news:H3******** ***********@new s4.e.nsc.no...
Hello,

I have a question regarding stored procedure desing that provides the
optimal performance. Let's say we have a table Products that consists of
three columns: Name, Status, RegistrationTim e. All columns are indexed and
users should be able to lookup data by any of the columns. We have two
main options to design stored procedures for data retrieval:

1. Design separate stored procedures for each search criteria:
LookupProductsB yName, LookupProductsB yStatus, LookupProductsB yTime.

2. Write a generic stored procedure that will fit any search criteria:

CREATE PROCEDURE GetProducts (
@Name varchar(20),
@Status int = NULL,
@FromTime datetime = NULL,
@ToTime datetime = NULL)
AS BEGIN
SELECT
[Name],
[Status],
[RegistrationTim e]
FROM [Products]
WHERE [Name]=CASE
WHEN @Name<>NULL THEN @Name
ELSE [Name]
END
AND [Status]=CASE
WHEN @Status<>NULL THEN @Status
ELSE [Status]
END
AND [RegistrationTim e]>=CASE
WHEN @FromTimestamp< >NULL THEN @FromTimestamp
ELSE [RegistrationTim e]
END
AND [RegistrationTim e]<=CASE
WHEN @ToTimestamp<>N ULL THEN @ToTimestamp
ELSE [RegistrationTim e]
END
ORDER BY [RegistrationTim e]
END;

The second option is very attractive, because it is obviously easier to
maintain such code. However, I am a little concerned about performance of
such stored procedure. It is not possible to foresee what index should be
used, index can only be selected each during procedure execution, because
search criteria can include either Name, Status or RegistrationTim e. Will
it make this SP inefficient? Or perormance difference in such case is not
big (if any) and we should choose the second option because of its
significant code reduction?

Thanks in advance

Vagif Abilov
va***@online.no


This article might help:

http://www.sommarskog.se/dyn-search.html

Simon
Jul 20 '05 #2
if you choose second option, dont' forget that expressions such as
@Status<>NULL never evaluate to true even if they are syntactically
valid, but you problably want to evaluate @status IS NOT NULL

Jul 20 '05 #3
Hi,
Step by step.

1.) Create Table as
CREATE TABLE [Products] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[Name] [varchar] (20) NOT NULL ,
[Status] [int] NOT NULL ,
[RegistrationTim e] [datetime] NOT NULL ,
CONSTRAINT [pk_Products] PRIMARY KEY CLUSTERED
(
[ID]
) ON [PRIMARY]
) ON [PRIMARY]
GO

2.) Fill random rows. Exactly 262144 rows
3.) Create Indexes as
CREATE INDEX [Products2] ON [dbo].[Products]([Name]) ON [PRIMARY]
CREATE INDEX [Products3] ON [dbo].[Products]([Status]) ON [PRIMARY]
CREATE INDEX [Products4] ON [dbo].[Products]([RegistrationTim e]) ON
[PRIMARY]
4.) Create Proc as
create PROCEDURE GetProducts (
@Name varchar(20),
@Status int = NULL,
@FromTime datetime = NULL,
@ToTime datetime = NULL)
AS BEGIN
SELECT
[Name],
[Status],
[RegistrationTim e]
FROM [Products]
WHERE [Name]=CASE
WHEN @Name IS NOT NULL THEN @Name
ELSE [Name]
END
AND [Status]=CASE
WHEN @Status IS NOT NULL THEN @Status
ELSE [Status]
END
AND [RegistrationTim e]>=CASE
WHEN @FromTime IS NOT NULL THEN @FromTime
ELSE [RegistrationTim e]
END
AND [RegistrationTim e]<=CASE
WHEN @ToTime IS NOT NULL THEN @ToTime
ELSE [RegistrationTim e]
END
ORDER BY [RegistrationTim e]
END
5) And analyse execution plan (Query: GetProducts @Name='ab1')

|--Sort(ORDER BY:([Products].[RegistrationTim e] ASC))
|--Clustered Index
Scan(OBJECT:([Prod430D].[dbo].[Products].[pk_Products]),
WHERE:((([Products].[Name]=If ([@Name]<>NULL) then [@Name] else
[Products].[Name] AND [Products].[Status]=If ([@Status]<>NULL) then
[@Status] else [Products].[Status]) AND [Products].[RegistrationTim e]>=If
([@FromTime]<>NULL) then [@FromTime] else [Products].[RegistrationTim e]) AND
[Products].[RegistrationTim e]<=If ([@ToTime]<>NULL) then [@ToTime] else
[Products].[RegistrationTim e]))

Wrong - Clustered Index Scan

6)Create index as
CREATE NONCLUSTERED INDEX [Products22] ON [dbo].[Products]
([RegistrationTim e] ASC, [Name] ASC, [Status] ASC )
And goto 5)

|--Index Scan(OBJECT:([Prod430D].[dbo].[Products].[Products22]),
WHERE:((([Products].[Name]=If ([@Name]<>NULL) then [@Name] else
[Products].[Name] AND [Products].[Status]=If ([@Status]<>NULL) then
[@Status] else [Products].[Status]) AND [Products].[RegistrationTim e]>=If
([@FromTime]<>NULL) then [@FromTime] else [Products].[RegistrationTim e]) AND
[Products].[RegistrationTim e]<=If ([@ToTime]<>NULL) then [@ToTime] else
[Products].[RegistrationTim e]) ORDERED FORWARD)
Yeah OK Index Scan

Warning:

Creating Procedure as
create PROCEDURE GetProducts1 (
@Name varchar(20),
@Status int = NULL,
@FromTime datetime = NULL,
@ToTime datetime = NULL)
AS BEGIN
SELECT
[Name],
[Status],
[RegistrationTim e]
FROM [Products]
WHERE ([Name]=@Name or @Name is null)
AND ([Status]=@Status or @Status is NULL)
AND ([RegistrationTim e] = @FromTime or @FromTime is null)
AND ([RegistrationTim e]= @ToTime or @ToTime is null)
ORDER BY [RegistrationTim e]
END;

Is very bad idea because exec time grow dramatically.

Conclusion
Solution <Write a generic stored procedure > is acceptable with good indexes
in tables.
Jul 20 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2289
by: Dragonhunter | last post by:
Hello, The aspfaq.com seems to really push stored procedures, and I hear the same advice here all the time. So I want to take the advice. Is it possible to create and practically maintain, delete, use, etc.. stored procedures soley from asp (i.e., no GUI or console- like being hosted on Brinkster)? The tutorial on aspfaq.com mentions...
12
8322
by: serge | last post by:
I have an SP that is big, huge, 700-800 lines. I am not an expert but I need to figure out every possible way that I can improve the performance speed of this SP. In the next couple of weeks I will work on preparing SQL statements that will create the tables, insert sample record and run the SP. I would hope people will look at my SP and...
3
5898
by: nandan | last post by:
Hi, Has any one ever compared the performance of calling a DataTable's Select method with a stored procedure doing the same thing? My point is: dataRows = DataTable.Select(filter) is better or Passing paramters to stored procedure? The datatable holds about 500-700 rows at any given time. If I select one of the approaches the business...
45
3362
by: John | last post by:
Hi When developing vb.bet winform apps bound to sql server datasource, is it preferable to use SELECTs or stored procedure to read and write data from/to SQL Server? Why? Thanks Regards
28
72355
by: mooreit | last post by:
The purpose for my questions is accessing these technologies from applications. I develop both applications and databases. Working with Microsoft C#.NET and Microsoft SQL Server 2000 Production and 2005 Test Environments. What is the purpose of a view if I can just copy the vode from a view and put it into a stored procedure? Should I be...
5
5072
by: Nesa | last post by:
I have a stored procedure that wraps a moderately complex query over 5, 6 related tables. The performance of the procedure is unacceptably slow as it takes on average 5-10 min to complete. To diagnose the problem, I copied the query in db2 command editor, and substituted the procedure parameters that appear in the query with fixed values with...
2
4084
by: jed | last post by:
I have created this example in sqlexpress ALTER PROCEDURE . @annualtax FLOAT AS BEGIN SELECT begin1,end1,deductedamount,pecentageextra FROM tax
1
1747
by: upstart | last post by:
Hi everyone…this is a tough one. You guys have been such a help before, hopefully you can point me in the right direction now. I have a Report I am working on that uses a stored procedure to pass along all off the parameters to the reporting generator (Crystal Reports) and I was currently trying to optimize it for my users, but am not sure...
2
4234
by: db2admin | last post by:
hi, I have query which runs great when optimization level is changed to 3 but does not run fine with default optimization level of 5. since this is a query in java code, i do not know how can i change optimization level of this one sql. also, developers are not comfortable with this. i am thinking of writing stored procedure in which i...
0
7412
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7355
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7748
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
5892
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5285
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4900
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3395
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3395
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1830
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.