Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 goto

Author  Topic 

wided
Posting Yak Master

218 Posts

Posted - 2013-03-26 : 10:12:07
I have a stored procedure that inserts data into tables according to conditions

I need to stop treatment as a condition to continue without knowing that I have no cursor, so I can not use break
example

if a
    insert into table1 ...
if b
    insert into table2 ...
if c
    insert into table3 ...

I want to stop the treatment if the condition b is good, should not pass the condition even if the condition c is c

I want to use goto: how

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-03-26 : 10:42:59
You can use else clauses like shown in the example below.
declare @x int; set @x = 2;

if @x > 3
begin
select 'GT 3';
end
else if @x > 2
begin
select 'GT 2'
end
else if @x > 1
begin
select 'GT 1';
end
Go to Top of Page

wided
Posting Yak Master

218 Posts

Posted - 2013-03-26 : 10:52:40
there is another way because my reqêtes are long and I may be wrong in the else
Go to Top of Page

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-03-26 : 11:19:52
Even if the code block in each if/else clause is long, it should work correctly as long as you wrap each block in a begin/end construct as I have shown in the example.
Go to Top of Page

wided
Posting Yak Master

218 Posts

Posted - 2013-03-26 : 11:50:51
OK
Go to Top of Page

russell
Pyro-ma-ni-yak

5072 Posts

Posted - 2013-03-26 : 12:27:28
http://msdn.microsoft.com/en-us/library/ms180188(v=sql.110).aspx
Go to Top of Page

wided
Posting Yak Master

218 Posts

Posted - 2013-03-26 : 12:53:57
Branch_One:
SELECT 'Jumping To Branch One.'
GOTO Branch_Three; --This will prevent Branch_Two from executing.

i want to exit treatment and not GOTO Branch_X

what can i do
Go to Top of Page

russell
Pyro-ma-ni-yak

5072 Posts

Posted - 2013-03-26 : 13:01:11
That's exactly what it does. YOU decide where to put the GOTOs


DECLARE @Counter int;
SET @Counter = 1;
WHILE @Counter < 10
BEGIN
SELECT @Counter
SET @Counter = @Counter + 1
IF @Counter = 4 GOTO Branch_One --Jumps to the first branch.
IF @Counter = 5 GOTO Branch_Two --This will never execute.
END
Branch_One:
SELECT 'Jumping To Branch One.'
GOTO The_End; --This will prevent Branch_Two from executing.
Branch_Two:
SELECT 'Jumping To Branch Two.'
The_End:
Go to Top of Page
   

- Advertisement -