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>
Anonymous User
02-Feb-2019It worked well.
sanu palata
06-Jul-2015