Sql – How to use IF statement in SQL Server 2005

if statementsqlsql-server-2005stored-procedurestsql

This is the scenario I would like to have in my INSERT in a stored procedure.

Tables:

tblRate

  • RateID (pk)
  • Rate money
  • Days int
  • isDailyRate bit

tblBooking

  • Totals money

In my vb app this is the statement. How would I translate this into T-SQL?

 if !isDaily = True then
      !Totals = (!Days * !Rate)
 else
      !Totals = !Rate
 end if

This is my stored procedure:

Create PROCEDURE [dbo].[sp_tblBooking_Add] 
   (
    @RateID     bigint,
    @Rate       money,
    @Days       int,
    @CheckOUT   datetime
   )
AS
BEGIN
    --Below is the logic I want. I can't get the right syntax

    --Declare @myTotals as money
    --Declare @myCheckOut as DateTime

    --if (Select isDailyRate FROM tblRates WHERE (RateID = @RateID)) = True THEN
    --  set myTotals = (@Rate * @Days)
    --  set @CheckOUT   = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) + @Days, '12:00') 
    --Else
    --  set myTotals = @Rate
    --  set @CheckOUT   = GETDATE()

    --End if

    INSERT INTO tblBooking(Totals, CheckOUT)
    VALUES(@myTotals, @myCheckOut); 
END

Best Answer

Use the CASE expression:

INSERT INTO tblBooking (Totals, CheckOUT)
SELECT 
  CASE 
    WHEN idDailyRate = 1 THEN @Rate * @Days 
    ELSE @rate 
  END,
  CASE 
    WHEN idDailyRate = 1 THEN DATEADD(DAY, 
                                      DATEDIFF(DAY, 0, GETDATE()) + @Days, 
                                      '12:00')
    ELSE GETDATE()
  END
FROM tblRates 
WHERE RateID = @RateID;

Or, if they are scalar values, then you can select them into a variables and insert them instead of INSERT ... INTO ... SELECT.


Update 1

Like this:

Declare @myTotals as money;
Declare @myCheckOut as DateTime;

SELECT 
  @myTotals = CASE 
                WHEN idDailyRate = 1 THEN @Rate * @Days 
                ELSE @rate 
              END,
  @myCheckOut = CASE 
                  WHEN idDailyRate = 1 THEN DATEADD(DAY, 
                                                    DATEDIFF(DAY, 0, GETDATE()) + @Days, 
                                                    '12:00')
                  ELSE GETDATE()
                END
FROM tblRates 
WHERE RateID = @RateID;

INSERT INTO tblBooking (Totals, CheckOUT) VALUES(@myTotals, @myCheckOut ); 

But this will give you an error, if there is more than value returned from this table tblRates into those variables.