【问题标题】:Using if/else in stored procedure with calculation在存储过程中使用 if/else 进行计算
【发布时间】:2014-04-28 07:23:16
【问题描述】:

在我的存储过程中,我现在尝试将 FEE 添加到我的销售中。

  • 如果 item_price 大于 69,则费用应为 6
  • 如果 item_price
  • 如果 item_price

我尝试将它添加到我的 SELECT 语句中,但我不知道如何正确插入它。

   AS 'Income inc VAT, ex Discount',
   case when item_price > 69 then 6
   case when item_price <= 69 then 3
   else 1
   AS 'fee'

为了举例说明我如何尝试实现它,我添加了一些 select 语句...

解决方案: 在我的选择语句中,我根据我得到的很好的答案添加了这段代码,它起作用了:

       case when item_price > 69 then 6 
       when item_price <= 69 then 3 
       else 1
       end
       AS 'Fee'

【问题讨论】:

    标签: sql-server-2008 select stored-procedures economics


    【解决方案1】:

    你应该使用case语句:

    凭记忆写:

    insert into fee (fee_value)
    select 
      case when item_price > 69 then 6
      case when item_price <= 69 then 3
      else 1
    end
    

    等等……

    或者,也许你想使用变量:

    declare @fee int
    
    if @item_price > 69 
     set @fee = 6
    

    ...

    insert into fee(fee_value) 
    values (@fee)
    

    或者其他方式:

    declare @item_price int  = 12
    
    declare @fee int
    
    SELECT
      @fee = case 
               when @item_price > 69 then 6
               when @item_price between 13 and 69 then 2
               else 1
             end
    
    select @fee   
    

    【讨论】:

    • 为此我必须先在数据库中创建一个费用列?我不知道如何将其构建到我的选择语句中
    • @Lebowski 我不知道你真正想做什么......而且我不知道你想如何使用你的计算。我的解决方案展示了如何调整费用计算。
    • @Lebowski 如果您只想选择费用,您可以使用我的第一个示例,无需 INSERT 部分声明
    • 您不需要第二个“案例”。尝试'当 item_price > 69 then 6 when item_price
    猜你喜欢
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 2015-05-22
    相关资源
    最近更新 更多