在存储过程查询中使用if语句?

时间:2019-12-11 00:15:07

标签: sql-server tsql stored-procedures cfstoredproc

我正在尝试将ColdFusion查询转换为存储过程。我原来的查询如下

UPDATE Products
SET Active = 1,
    Pounds = #lbs#,
    Ounces = #ozs#,
    Qty = #Qty#,
    PrevQty = #GetItem.Qty#,
    PrevWMQty = #GetItem.Qty#,
    PrevGoogleQty = #GetItem.Qty#,
    <cfif Cost NEQ GetItem.OurCost>
        PrevOurCost = #GetItem.OurCost#,
    </cfif>
    OurCost = #Cost#
WHERE ItemID = '#fixedItemID#'

您可以看到查询中包含IF语句,因此如果满足某些条件,它将更新这些字段。如果不满足这些条件,则它将不包括在更新中。

所以我想要这样的东西,但是我不确定这在存储过程中是可能的

CREATE PROCEDURE [dbo].[spUpdateQty] 
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE Products
    SET Active = 1,
        Pounds = @var1,
        Ounces = @var2,
        Qty = @var3,
        PrevQty = @var4,
        PrevWMQty = @var5,
        PrevGoogleQty = @var6,
        IF (@var7 >= @var8)
        BEGIN
            PrevOurCost = @var7,
        END
        OurCost = @var8
    WHERE ItemID = @var9
END

我基本上希望传递可选参数,并根据其值更新或不更新该字段。我讨厌必须为每种IF语句针对每种可能情况编写单独的查询。那么这有可能还是我会走错路呢?

2 个答案:

答案 0 :(得分:2)

您可以使用case表达式有条件地更新列,从而避免重复更新语句。

例如

UPDATE Products SET
    Active = 1,
    Pounds = @var1,
    Ounces = @var2,
    Qty = @var3,
    PrevQty = @var4,
    PrevWMQty = @var5,
    PrevGoogleQty = @var6,
    PrevOurCost = case when @var7 >= @var8 then @var7 else PrevOurCost end,
    OurCost = @var8
WHERE ItemID = @var9

答案 1 :(得分:1)

有多种方法可以实现

您可以使用案例声明

      UPDATE Products
      SET Active = 1,
          Pounds = @var1,
          Ounces = @var2,
          Qty = @var3,
          PrevQty = @var4,
          PrevWMQty = @var5,
          PrevGoogleQty = @var6,
          PrevOurCost = CASE WHEN @var7 >= @var8 THEN @var7 ELSE PrevOurCost END,
          OurCost = @var8
        WHERE ItemID = @var9

或者您可以在UPDATE语句之外使用IF语句

IF (@var7 >= @var8)
BEGIN

      UPDATE Products
      SET Active = 1,
          Pounds = @var1,
          Ounces = @var2,
          Qty = @var3,
          PrevQty = @var4,
          PrevWMQty = @var5,
          PrevGoogleQty = @var6,
          PrevOurCost = @var7,
          OurCost = @var8
        WHERE ItemID = @var9
END
ELSE
BEGIN
      UPDATE Products
      SET Active = 1,
          Pounds = @var1,
          Ounces = @var2,
          Qty = @var3,
          PrevQty = @var4,
          PrevWMQty = @var5,
          PrevGoogleQty = @var6,
          OurCost = @var8
        WHERE ItemID = @var9

END