Friday, August 16, 2013

Recursion Using Stored Procedure and executing it

Recursion can be achieved using Stored Procedure. In this example root of the child can be obtained by using such method of Recursion.
here same stored procedure is called by itself using exec method passing parameters which makes it to call itself recursively.

This type of recursion is very useful in case of parent child hierarchical data where we have to get the root or origin of the data.
few example cases are:
1. hierarchical structure of menu.
2. hierarchical ledger where the one ledger should be precisely have its parent defined.
3. categorization of data in parent child relation.

example:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Gautam>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
Create PROCEDURE GetRoot
  
    @Component as int
    ,@Root as int OUTPUT
AS
BEGIN
if ((select ParenID  from tbl_BudgetHeadMaster where BudgetHeadMasterID =@Component )is not null)
begin
    set  @Root= (select ParenID  from tbl_BudgetHeadMaster where BudgetHeadMasterID =@Component and ParenID is not null)
    exec GetRoot @Root,@Root   -----Calls itself
  
    end
    else
    begin
    set @Root= @Component
    select @Root
    end
END
GO

---to run the Procedure
  exec getroot 117,@Root =@id  output;