blog

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

Checking IF…ELSE condition in Stored Procedure SQL Server

AVADHESH PATEL 138433 06-Sep-2012

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>


Updated 18-Sep-2014
Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)

Leave Comment

Comments

Liked By