2013-03-01 62 views
1

我正在嘗試對sql表執行批量更新,但我不明白邏輯等效。我想要做的,在僞代碼是:基於日期時間將列更新爲整數

UPDATE mytable 
SET mycolumn = (pull down the datetime from mycolumn2. if the year of that datetime is not equal to 2013, then mycolumn = 24. if the year is 2013, then mycolumn = 24 - number of months in that datetime) 

我只是真的不知道從哪裏開始在SQL中實現這種邏輯。有沒有人對我有任何提示或方向?根據需要

感謝

+2

*** *** SQL只是*結構化查詢語言* - 許多數據庫系統中使用的語言,而不是AA的數據庫產品。 ..很多東西都是特定於供應商的 - 所以我們真的需要知道您正在使用的數據庫系統**(以及哪個版本)...... – 2013-03-01 16:46:31

+0

@marc_s我正在使用Microsoft SQL Server 2008 ..對不起 – proseidon 2013-03-01 16:48:03

回答

1
UPDATE myTable 
SET mycolumn = CASE WHEN DATEPART(year, mycolumn2) = 2013 
         THEN 24 - DATEPART(month, mycolumn2) 
        ELSE 24 
       END 

調整日期語法RDBMS。

0
UPDATE mytable 
SET mycolumn = CASE WHEN YEAR(mycolumn2) <> 2013 
        THEN 24 
        WHEN YEAR(mycolumn2) = 2013 
        THEN 24 - mycolumn 
       END 
0

使用Simple Case statment:

update mytable 
set mycolumn = 24 - case year(mycolumn2) 
         when 2013 then month(mycolumn2) 
         else 0 
        end