2013-02-06 78 views
0

我有一個列如book,startyear,endyearauthor列表。更新在同一表中的兩個條件的表

我需要startyearendyear列同時根據下列條件更新,

STARTYEAR = ENDYEAR where STARTYEAR=0 and ENDYEAR != 0 
also 
ENDYEAR = STARTYEAR where ENDYEAR =0 and STARTYEAR != 0 

這是可能的

UPDATE Table SET STARTYEAR = ENDYEAR WHERE STARTYEAR=0 AND ENDYEAR<>0; 
UPDATE Table SET ENDYEAR = STARTYEAR WHERE ENDYEAR =0 AND STARTYEAR<>0; 

我怎麼能在一個查詢寫這2個查詢?

回答

3
update table 
set 
startYear = case when startyear = 0 and endyear<>0 then endyear else startYear end, 
endYear = case when endyear = 0 and startyear <> 0 then startyear else endYear end 
where startyear = 0 or endyear = 0; 
+0

你可以只讓他們的機器人= 0,因爲這是希望的結果當任爲0 – Techmonk

+0

@Techmonk不,你應該重新閱讀的問題,我們的目標是不設置這些值0 –

+0

你是對的。 ..這是相反的方式! – Techmonk

1

您可以使用或更新bot字段,除非您有觸發器阻止您在startyear = endyear = 0;

UPDATE Table SET STARTYEAR = STARTYEAR+ ENDYEAR, ENDYEAR = STARTYEAR+ENDYEAR WHERE STARTYEAR=0 OR ENDYEAR=0 
+0

+1,聰明而簡單的想法。唯一的風險是空值:startYear = 0,endYear IS NULL所以0 + NULL = NULL,而不是0.只需添加一個聚合,它會很好(如果它們是可空的)。 –

0

在一條語句中無法更新多個表,但是,您可以使用事務,以確保兩個更新語句都像一個處理。您也可以對其進行批處理以避免往返。

BEGIN TRANSACTION 

UPDATE Table SET STARTYEAR = ENDYEAR WHERE STARTYEAR=0 AND ENDYEAR<>0; 

UPDATE Table SET ENDYEAR = STARTYEAR WHERE ENDYEAR =0 AND STARTYEAR<>0; 

COMMIT 

,但在你的情況,你也可以使用像在this post答案。

0

這應該工作,

update test 
    set startyear = (case when startyear = 0 AND endyear <> 0 then endyear else startyear end), 
     endyear = (case when endyear = 0 AND startyear <> 0 then startyear else endyear end); 
3

另一種方法是:

UPDATE Table 
SET STARTYEAR = STARTYEAR + ENDYEAR 
    , ENDYEAR = STARTYEAR + ENDYEAR 
WHERE STARTYEAR = 0 AND ENDYEAR <> 0 
    OR ENDYEAR = 0 AND STARTYEAR <> 0 ; 

但我實在看不出這樣做的任何理由。您可以在交易中使用2種報表方式。它甚至可能比任何令人費解的單一陳述更有效率。

相關問題