Creating an Index within a Stored Procedure
Is it better to create an index with a stored procedure? Well, you can do it -- but this solution causes another problem. Here's how to solve both at once.
Join the DZone community and get the full member experience.
Join For FreeIntroduction
One of my friends asked: "Is it better to create an Index within a Stored Procedure?" While it depends on the columns used in a stored procedure to improve the Join performance and Drop the stored procedure after getting the desired output and just before the ending...
Technical Answer
...yes, we can create an Index within the Stored Procedure.
Now, We Have to Think What Our Answer means
Technically, what my friend mentioned in the scenario is possible. But performance wise, it’s again a problematic solution. That’s means to solve something we again create another problem. To understand it properly let’s take an example of such kind of Stored Procedure.
IF OBJECT_ID(N'[dbo].[sproc_StudentDetails]', N'P')IS NOT NULL
DROP PROCEDURE [dbo].[sproc_StudentDetails];
GO
CREATE PROCEDURE [dbo].[sproc_StudentDetails]
(
@p_StdClass INT
)
AS
BEGIN
-- Creating Non Clustered Index on IDNO
CREATE NONCLUSTERED INDEX IX_NC_IDNO_StdDtl
ON tbl_StudentDetails(IDNO);
CREATE NONCLUSTERED INDEX IX_NC_IDNO_StdMarks
ON tbl_StudentMarks(IDNO);
-- Making JOIN on IDNO for Performance Reason
SELECT a.Roll, a.StdName, b.Marks1, b.Marks2
FROM tbl_StudentDetails AS a
INNER JOIN tbl_StudentMarks AS b ON a.IDNO = b.IDNO;
-- Droping the Index
DROP INDEX IX_NC_IDNO_StdDtl ON tbl_StudentDetails;
DROP INDEX IX_NC_IDNO_StdMarks ON tbl_StudentMarks;
END
GO
Here in this example if we look carefully the No clustered Index is created and after successful joining it again drops.
It is technically perfect.
So, What Is the Problem...
SELECT a.Roll, a.StdName, b.Marks1, b.Marks2
FROM tbl_StudentDetails AS a
INNER JOIN tbl_StudentMarks AS b ON a.IDNO = b.IDNO;
The performance of the JOIN condition is increased due to a non clustered index. So we think that we got the performance gain...but, in fact, we did NOT. Always understand fully before implementing.
When the Index created the Index table and the Statistical table, both are updated, so making an index within a stored procedure again takes a long time to create.
By the index creation we solve the Join performance, but Index creation time is again a pain point and slows down the performance of a stored procedure.
Hope you like it.
Published at DZone with permission of Joydeep Das, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments