-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.

Andrew Savinykh
  • 25,351
  • 17
  • 103
  • 158
Sarthak
  • 51
  • 3
  • 10

2 Answers2

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.

Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569
  • 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. – Sarthak Feb 17 '15 at 08:34
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.

hussein shaib
  • 108
  • 1
  • 9
  • 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. – Sarthak Feb 17 '15 at 07:30