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
 General SQL Server Forums
 New to SQL Server Programming
 Nested If Statements

Author  Topic 

csosa
Starting Member

5 Posts

Posted - 2011-04-09 : 12:36:22
Hi I'm experimenting creating a stored procedure with multiple if statements here is what I have


CREATE PROCEDURE caco
-- Add the parameters for the stored procedure here
@temp1 int = 0,
@temp2 int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
IF (@temp1 <> 0)
SELECT * FROM tb_clients WHERE ID_Client = @temp1
IF (@temp2 <> 0)
PRINT 'Test1'
ELSE
PRINT 'Test2'
ELSE
PRINT 'Test3'
END
GO


Please Note that with this code I get an error 'Incorrect syntax near the keyword 'ELSE' '(THE SECOND ELSE).

If I remove the Select statement everything works well.

Any ideas

Thanks

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-04-09 : 12:47:18
You need a begin and end keywords if there is more than one statement that you want inside an if or else block.
CREATE PROCEDURE caco
-- Add the parameters for the stored procedure here
@temp1 int = 0,
@temp2 int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
IF (@temp1 <> 0)
BEGIN
SELECT * FROM tb_clients WHERE ID_Client = @temp1
IF (@temp2 <> 0)
PRINT 'Test1'
ELSE
PRINT 'Test2'
END
ELSE
PRINT 'Test3'
END
GO
Go to Top of Page
   

- Advertisement -