0

My inline table function basically prints out numbers, from 1 to the number that is input in the function. Since I'm new to SQL Server I am not sure how to implement a while loop inside a function. My implementation is below. As expected i get a lot compiler errors at WHILE, BEGIN, THEN. Can anyone suggest how can i improve the code. Thanks!

CREATE FUNCTION num_F(@nnn INT)
RETURNS TABLE
AS
RETURN (SELECT CASE 
                WHEN @nnn = 0
                    THEN NULL
                    ELSE WHILE dbo.num_F(@nnn) > 0
                          BEGIN
                          THEN dbo.num_F(@nnn)
                          SET dbo.num_F(@nnn) = dbo.num_F(@nnn)-1
                         END
                         GO
                END as First_Col
        ORDER BY First_Col ASC)        

1 Answer 1

1

simplest ways is by using a common table expression (CTE)

CREATE FUNCTION Numfunctn1 (@num INT)
RETURNS TABLE
AS
    RETURN(
      WITH cte
           AS (SELECT 1 id
               UNION ALL
               SELECT id + 1
               FROM   cte
               WHERE  id < @num)
      SELECT *
       FROM   cte) 


SELECT *
FROM   Numfunctn1(10) 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks but is this an inline table function ?. Can you help to form an inline table function
@user3760741 check now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.