Case语句总是在存储过程中跳过ELSE

时间:2015-01-13 08:05:10

标签: sql sql-server-2008 stored-procedures case table-valued-parameters

我试图在sql存储过程中插入期间使用CASE语句,如下所示:

INSERT INTO [dbo].[OfferPrice]
            (OfferId,Price,DefaultPrice,SalePrice,
             SaleFromDate,SaleToDate)
SELECT tvp.OfferId   AS OfferId,
       CASE
         WHEN @Price IS NOT NULL THEN @Price
         WHEN @Price IS NULL
              AND tvp.SalePrice IS NOT NULL
              AND Getutcdate() >= tvp.SaleFromDate
              AND Getutcdate() < tvp.SaleToDate THEN tvp.SalePrice
         WHEN @Price IS NULL
              AND tvp.SalePrice IS NULL THEN tvp.DefaultPrice
         ELSE 0
       END AS Price,
       tvp.DefaultPrice AS DefaultPrice,
       tvp.SalePrice AS SalePrice,
       tvp.SaleFromDate AS SaleFromDate,
       tvp.SaleToDate AS SaleToDate
FROM   @OfferPriceTVP tvp
       LEFT JOIN [dbo].OfferPrice dop
              ON dop.OfferId = tvp.OfferId
WHERE  dop.OfferId IS NULL 

问题是CASE总是跳到ELSE,即使之前的陈述是真的。我做错了什么?

编辑:

这是@OfferPriceTVP:

CREATE TYPE [dbo].[TVP_OfferPrice] AS TABLE
(
    OfferId INT NOT NULL PRIMARY KEY, CountryId INT NOT NULL, VatRateId INT, DefaultPrice decimal(16, 4), SalePrice decimal(16, 4),
    SaleFromDate datetime, SaleToDate datetime
);

这里是我现在尝试做的插入(即使没有日期,它应该将价格设置为默认值吗?):

DECLARE @OfferPriceTVP AS [dbo].[TVP_OfferPrice]
INSERT INTO @OfferPriceTVP (OfferId,CountryId,VatRateId,DefaultPrice,SalePrice,SaleFromDate,SaleToDate)
VALUES (10006805,2,1,1,1,NULL,NULL),
(10006806,1,1,2,1,NULL,NULL),
(10006807,1,1,3,1,NULL,NULL),
(10006808,1,1,4,1,NULL,NULL),
(10006809,1,1,5,1,NULL,NULL),
(10006810,1,1,6,2,NULL,NULL);
EXEC [dbo].[TVP_OfferPrice] @OfferPriceTVP;
GO

2 个答案:

答案 0 :(得分:1)

我认为,或许,如果没有销售日期,您的意图是采用销售价格(如果有)或默认价格。

如果是这种情况,那么只需忽略第三个SalePrice IS NULL中的WHEN检查并使用COALESCE

   CASE
     WHEN @Price IS NOT NULL THEN @Price
     WHEN @Price IS NULL
          AND tvp.SalePrice IS NOT NULL
          AND Getutcdate() >= tvp.SaleFromDate
          AND Getutcdate() < tvp.SaleToDate THEN tvp.SalePrice
     WHEN @Price IS NULL
          THEN COALESCE(tvp.SalePrice,tvp.DefaultPrice)
     ELSE 0
   END AS Price

答案 1 :(得分:0)

与NULL的比较始终为false。您的表中没有销售日期。销售期检查

Getutcdate() >= tvp.SaleFromDate AND Getutcdate() < tvp.SaleToDate

总会失败。

这意味着,如果@Price为NULL并且SalePrice不是,则只有ELSE语句有效。