2

这是我希望INSERT在存储过程中使用的场景。

表:

tbl速率

  • RateID (pk)
  • 给钱打分
  • 天数
  • isDailyRate 位

tblBooking

  • 总钱

在我的 vb 应用程序中,这是声明。我如何将它翻译成 T-SQL?

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

这是我的存储过程:

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
4

1 回答 1

2

使用CASE表达式:

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;

或者,如果它们是标量值,那么您可以将它们选择到变量中并插入它们而不是INSERT ... INTO ... SELECT.


更新 1

像这样:

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 ); 

但这会给你一个错误,如果从这个表返回的值超过tblRates这些变量。

于 2013-02-17T07:17:27.327 回答