-2

I am having a recursive loop of a stored procedure and i want to stop the execution of that recursive loop on a validation and return an empty table. How can i do that?

This is some sample code :

alter procedure Searching
(parameters)
begin
  do something
  if(validation)
     --exit here
  else
    exec Searching(parameters);
end

and i have another question of how to declare a global variable in sql? which should not lose it's scope from one stored procedure to another.

7
  • This is what return statement is for. Commented Feb 17, 2015 at 6:49
  • Global variables Commented Feb 17, 2015 at 6:51
  • @zespri yes but return statement not making the loop come out of the recursion. Commented Feb 17, 2015 at 6:54
  • What do you mean? You have a tail recursion it will end naturally. Commented Feb 17, 2015 at 6:56
  • yes kinda like that. the do something part is doing the logic part then recursion calling going for the same logic on the next column. Commented Feb 17, 2015 at 7:06

2 Answers 2

1

T-SQL is a really poor choice for recursion. It won't allow more than 32 levels of nesting, see @@NESTLEVEL:

When the maximum of 32 is exceeded, the transaction is terminated.

As always, the answer is to think in sets, use a SELECT instead of a stored procedure. Read Recursive Queries Using Common Table Expressions.

As to why your example doesn't work: you obviously made a mistake in the code which you did not post.

Sign up to request clarification or add additional context in comments.

1 Comment

well recursion is working fine in my case, the problem is in one of the condition i want it nt to do the logic steps further on and just terminate execution.
0

you must break down the condition of the recursion so that it don't continue after you return. you can make use off an integer that is decremented after each loop when it is negative u can stop execution.

1 Comment

actually am already using a counter for the execution of the procedure on column, but the problem is something else, like actually am getting two values for each search on each column, when either of the two values comes as null, i want the procedure to stop the execution and just return an empty table.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.