在Sql Server视图中的if语句

时间:2011-06-02 18:43:56

标签: sql

如果销售日期已过期或尚未生效,我想将saletype设置为0,但仅当assignDate为true时才设置。我怎样才能在视图中构建它?

SELECT     dbo.ItemStore.SaleType, dbo.ItemStore.SpecialBuyFromDate AS SaleStartDate , 
dbo.ItemStore.SpecialBuyToDate AS SaleEndDate , dbo.ItemStore.AssignDate
FROM         dbo.ItemMainAndStoreView

3 个答案:

答案 0 :(得分:3)

使用CASE表达式

您需要允许GETDATE()时间方面,因此我的DATEADD/DATEDIFF会删除时间组件以进行正确的日期范围检查。

对于SQL Server 2008+,您只需使用CAST(GETDATE()作为日期)

SELECT
     CASE
        WHEN DATEADD(day, 0, DATEDIFF(day, 0, GETDATE()))
                BETWEEN dbo.ItemStore.SpecialBuyFromDate AND dbo.ItemStore.SpecialBuyToDate
            THEN dbo.ItemStore.SaleType
            ELSE 0
     END AS SaleType
     dbo.ItemStore.SpecialBuyFromDate AS SaleStartDate , 
     dbo.ItemStore.SpecialBuyToDate AS SaleEndDate,
     CASE
 FROM    
     dbo.ItemMainAndStoreView

答案 1 :(得分:1)

利用Case..When可以轻松解决您的问题

例如:

USE AdventureWorks2008R2;
GO
SELECT   ProductNumber, Name, 'Price Range' = 
      CASE 
         WHEN ListPrice =  0 THEN 'Mfg item - not for resale'
         WHEN ListPrice < 50 THEN 'Under $50'
         WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
         WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
         ELSE 'Over $1000'
      END
FROM Production.Product
ORDER BY ProductNumber ;
GO

答案 2 :(得分:1)

SELECT case 
    when getdate() between dbo.ItemStore.SpecialBuyFromDate 
        and dbo.ItemStore.SpecialBuyToDate 
    then dbo.ItemStore.SaleType 
    else 0 end as SaleType,
    dbo.ItemStore.SpecialBuyFromDate AS SaleStartDate,  
    dbo.ItemStore.SpecialBuyToDate AS SaleEndDate 
FROM dbo.ItemMainAndStoreView