2011-06-02 53 views
1

如果銷售日期已過期或尚未激活,但僅當assignDate爲true,纔想將saletype設置爲0。我如何在視圖中構建它?如果在Sql Server視圖中聲明

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

回答

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 
+0

有趣的使用DATEADD(day,0,DATEDIFF(day,0,GETDATE()))來獲取當天的開始 – lambacck 2011-06-02 18:53:02

+0

@lambacck:最有效的方法來做到這一點http://stackoverflow.com/questions/1177449/最好的方法去除的時間,部分的,日期時間,在-SQL服務器/ 1177529#1177529 – gbn 2011-06-02 18:55:07

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 
+0

爲什麼不提供基於提供什麼OP代碼? – gbn 2011-06-02 18:50:48

+0

我認爲他只需要方向...即要學習的東西,而不是現成的代碼多數民衆贊成在 – 2011-06-02 18:55:40

+0

兩種方式都行。 – Ezi 2011-06-02 18:59:59

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 
+0

如果SpecialBuyToDate是今天00:00這失敗,因爲時間是20 :56 ...不是? – gbn 2011-06-02 18:56:59

+0

@gbn它取決於業務規則;有時結束日期的意思是在當天的00:00停止,有時在第二天的00:00停止,但這很好指出。 – RedFilter 2011-06-02 19:33:56