title: Is there any way to get the value without using the loop?
body: <pre><code>Id       DependentId
  -----    ------------
  2        5
  5        8
  8        6
  6        7
  7        NULL
  3        10
  10       15
  17       NULL
  15       NULL
  </code></pre>
  
  <p>I wrote a function that return 7 from above table if we pass the parameter 2.</p>
  
  <p>Other examples: return value is 15 if parameter value is 3.</p>
  
  <p>Return value will be 17 if input parameter is 17</p>
  
  <p>Function:</p>
  
  <pre><code>ALTER FUNCTION dbo.getValue
  (
   @Id INT
  )
  RETURNS INT
  AS
  BEGIN
      DECLARE @DependentId AS INT
      WHILE (1 = 1)
          BEGIN
              SELECT @DependentId = DependentId FROM dbo.givenTable WHERE  Id = @Id;
              IF (@DependentId IS NOT NULL)
                      SET @Id = @DependentId
              ELSE
                  BREAK;
          END 
          RETURN @Id
  END
  GO
  </code></pre>
  
  <p>Is there any way to get the value without using the loop?</p>