Home > DeveloperSection > Blogs > Checking IF…ELSE condition in Stored Procedure SQL Server

Checking IF…ELSE condition in Stored Procedure SQL Server


Database Database 
Ratings:
1 Comment(s)
 68972  View(s)
Rate this:

Checking IF…ELSE condition in Stored Procedure SQL Server

SQL IF...ELSE Statement used to test a condition. IF...ELSE Statement using in execution of a Transact-SQL statement (Store Procedure or T-SQL) and Trigger.
IF tests can be nested after another IF or following an ELSE. There is no limit to the number of nested levels.


IF condition is satisfied and the Boolean expression returns TRUE, it will executed IF Block SQL statement.
IF condition is not satisfied and the Boolean expression returns FALSE, it will executed ELSE Block SQL Statement query.

--CREATE PROCEDURE

CREATE PROCEDURE ELIGIBILITY

(

  @MaxAge INT --PARAMETER

)

AS

BEGIN

      IF(@MaxAge>=18) --CONDITION

            BEGIN

                  PRINT 'YOU ARE ELIGIBLE FOR ADMITION'--CONDITION TRUE

            END

      ELSE

            BEGIN

                  PRINT 'SORRY, YOU ARE NOT ELIGIBLE FOR ADMITION'--CONDITION FALSE

            END

END

Execute Procedure with parameter and see output

-- EXECUTE PROCEDURE

EXEC ELIGIBILITY 2

Output- SORRY, YOU ARE NOT ELIGIBLE FOR ADMITION

EXEC ELIGIBILITY 22

Output- YOU ARE ELIGIBLE FOR ADMITION

EXEC ELIGIBILITY 2

Output- SORRY, YOU ARE NOT ELIGIBLE FOR ADMITION

EXEC ELIGIBILITY 22

Output- YOU ARE ELIGIBLE FOR ADMITION

IF-ELSE Condition with Procedure and SQL-T

 --CREATE PROCEDURE

 CREATE PROCEDURE Check_Exist

(

@Id INT,

@Name VARCHAR(20),

@Address VARCHAR(20)

)

AS

BEGIN

      IF NOT EXISTS (SELECT [Id] FROM INFO WHERE [Id]=@Id)

      BEGIN

            INSERT INTO INFO VALUES(@Id,@Name,@Address)

            PRINT 'New Record Insert Successfuly'

      END

      ELSE

      BEGIN

            PRINT 'Id All Ready Exist'

      END

END

 --EXECUTE PROCEDURE WITH ARGUMENT

EXEC Check_Exist <id>,<name>,<address>


Thank you sir

By sanu palata on   one year ago
Thank you sir ,I am follow this syntax also use nested if else doing more example.  

Don't want to miss updates? Please click the below button!

Follow MindStick