Tuesday, November 24, 2015

Stored Procedures in MSSQL

Since we need to manage create first and then update on procedure alterations, its better to test whether the SP is already exists at first and if so, drop it and create it again.

For example we can follow the below way that will drop the SP each time its being run and create again instead of writing new update procedures.

 if exists (select * from dbo.sysobjects where id=object_id(N'[dbo].[procName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)  
      drop procedure [dbo].[procName]  
 GO  
 /************************************************************************  
      Stored Procedure Name:     dbo.procName  
      Creation Date:               2015-10-15   
      Copyright:                    http://techndj.blogspot.com/  
      Written by:                    http://techndj.blogspot.com/  
      Purpose:                    Why you write it  
      Input Parameters:          @paraOne  
                                    @paraTwo  
                                    @paraThree  
      Output Parameters:  
      Return Status:               0  
      Usage:  
                                    exec procName 11, 'ABC','DETAILS'  
      Local Variables:  
      Called By:  
      Calls:  
      Data Modifications:  
      Updates:  
      Date               Version          Author     Purpose  
      ---------------     ---------     ------     -------------------------  
 ************************************************************************/  
 CREATE PROCEDURE [dbo].[procName]  
      @paraOne int,  
      @paraTwo     varchar(100) = NULL,  
      @paraThree     varchar(255) = NULL  
 AS SET NOCOUNT ON  
 SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED  
 /*  
 YOUR PROCEDURE HERE  
 */  
 RETURN 0  
 GO  
 --GRANTING PERMISSION   
 GRANT EXECUTE ON dbo.procName TO EXECGroupName  
 GO  

Applying this format, its been always easy to manage alterations and maintain the version too.

No comments:

Post a Comment