Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Server: I wonder whta syntax error is near else

I’m tring to create a procedure. And when I set @age after setting @flag, something is wrong. But either I tried to delete set @age or set @flag it would work.

error:there is a syntax error near else

I wonder what caused this. Thanks for help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select * from sc
if exists(select *
                    from sysobjects
                    where name='pro5' and type ='P')
    drop procedure pro5
go

create procedure pro5 @stuNo char(10),@flag int output
as 
declare @age int
begin
        set @age=0
        set @flag=1
        if exists(select *
                  from sc
                  where sno=@stuNo)
            set @flag=0
            set @age=0
        else
                delete 
                from student
                where sno=@stuNO

end
return @age
go

declare @flag int
exec pro5 '991102',@flag output
if @flag=1
    print 'success'
else
    print 'failure'

>Solution :

You need to define a begin and end around all lines in your if statement which by default only assumes a single line belongs to the "if" block:

if exists(select * from sc where sno=@stuNo)
begin
    set @flag=0
    set @age=0
end
else
    delete 
    from student
    where sno=@stuNO

However you could simplify a little since you don’t need to also set age which is already 0:

create procedure pro5 @stuNo char(10), @flag int output
as 
declare @age int = 0;
    
if exists(select * from sc where sno = @stuNo)
  set @flag = 0
else
begin
  delete from student where sno = @stuNO;
  set @flag = 1;
end

return @age;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading