Its an example of a simple stored procedure using IF-Else in SQL .
First of all,we declared a variable ( @cnt ) to count no of rows that matches the condition ( @cnt=COUNT(*) ).
Select @cnt=COUNT(*) from tbl_X where AirlineCode = @AirlinesCode AND DestinationCode = @DestinationCode
Structure of IF Else like this :-
IF @cnt=0
Then
Insert New Record
Else
Update the Existing Record
Stored Procedure would be :-
USE [XXX]
GO
Create PROCEDURE [dbo].[sp_Admin_InsertIncreasedFare]
@AirlinesCode varchar(100),
@DestinationCode varchar(100),
@Amount decimal(18, 2)
AS
BEGIN
SET NOCOUNT ON;
declare @cnt int=0;
Select @cnt=COUNT(*) from tbl_X where AirlineCode = @AirlinesCode AND DestinationCode = @DestinationCode
-- If loop--
IF @cnt=0
Begin
Insert into tbl_X (AirlineCode,DestinationCode,Amount) VALUES (@AirlinesCode,@DestinationCode,@Amount)
END
Else
Begin
Update tbl_X Set Amount=@Amount where AirlineCode = @AirlinesCode AND DestinationCode = @DestinationCode
END
END
First of all,we declared a variable ( @cnt ) to count no of rows that matches the condition ( @cnt=COUNT(*) ).
Select @cnt=COUNT(*) from tbl_X where AirlineCode = @AirlinesCode AND DestinationCode = @DestinationCode
Structure of IF Else like this :-
IF @cnt=0
Then
Insert New Record
Else
Update the Existing Record
Stored Procedure would be :-
USE [XXX]
GO
Create PROCEDURE [dbo].[sp_Admin_InsertIncreasedFare]
@AirlinesCode varchar(100),
@DestinationCode varchar(100),
@Amount decimal(18, 2)
AS
BEGIN
SET NOCOUNT ON;
declare @cnt int=0;
Select @cnt=COUNT(*) from tbl_X where AirlineCode = @AirlinesCode AND DestinationCode = @DestinationCode
-- If loop--
IF @cnt=0
Begin
Insert into tbl_X (AirlineCode,DestinationCode,Amount) VALUES (@AirlinesCode,@DestinationCode,@Amount)
END
Else
Begin
Update tbl_X Set Amount=@Amount where AirlineCode = @AirlinesCode AND DestinationCode = @DestinationCode
END
END