Wednesday, January 5, 2011

Break vs Return

Suppose you have a set of codes and when a particular condition is true, you want to terminate or switch to another set of code, you can use Break commnad. I see sometimes people use return commnad for this. But there is a significant difference between these two. Consider this example
Usage of BREAK (select will be executed)
declare @j int
set @j=1
while 1=1
begin
print @i
if @j>10 break -It Terminate the Current Block
set @j=@j+1
end
select @j

declare @i int
set @i=1
while 1=1
begin
print @i
if @i>10 return It Terminate the Entire Block
set @i=@i+1
end
.select @i
Break Command-it just terminate the current block (created by if clause, while loop etc), but Return Command- will terminate the entire block

No comments:

Post a Comment