Showing posts with label Scalar valued Function. Show all posts
Showing posts with label Scalar valued Function. Show all posts

Friday, August 16, 2013

Recursion Using SQL User defined Function and calling scalar valued Function

GO
/****** Object:  UserDefinedFunction [dbo].[GetBudgetRoot]    Script Date: 10/03/2012 09:39:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Gautam>
-- Create date: <Create Date, ,>
-- Description:    <Description, To Get the Root ID for Budget Components ,>
--takes Component ID (BudgetHeadID Having ParenID not null) and Returns The Root with parenID Null
-- =============================================
Create FUNCTION [dbo].[GetBudgetRoot](@CompID int)

RETURNS int
AS
BEGIN
    -- Declare the return variable here
    Declare @RootID int;
  
    -- Add the T-SQL statements to compute the return value here
    ---Scalar-valued functions may be invoked where scalar expressions are used,
    ---including computed columns and CHECK constraint definitions. When invoking scalar-valued functions,
    -- at minimum use the two-part name of the function.
    if ((select ParenID  from tbl_BudgetHeadMaster where BudgetHeadMasterID =@CompID )is not null)
    begin
    set  @RootID= (select ParenID  from tbl_BudgetHeadMaster where BudgetHeadMasterID =@CompID and ParenID is not null)
   set @RootID =    dbo.GetBudgetRoot(@RootID)
  
    end
    else
    begin
    set @RootID= @CompID
  
    end


    RETURN @RootID;

END

---To Call

Declare @ID int
set @ID= dbo.GetBudgetRoot(119)
select @ID