2014-10-19 56 views
0

我將在的T-SQL中執行以下操作。如果記錄不存在於表1中,則更新表2,否則如果記錄存在更新表2具有來自表1的列

Table1由一些任意的行組成。 Table2由比Table1多的行組成,但存在的行是相同的,除了一列包含日期。

如果Table1中的一行存在於Table2中,我想更新Table2的日期列。
如果Table1中的行不存在於Table1中,我也想更新Table2的日期列。

我不能爲我的生活弄清楚發生這種情況的語法,因爲此存儲過程不會接受任何參數或輸出任何參數。

+0

如果記錄沒有在表1憑什麼值u會去更新在表2 – 2014-10-19 15:54:07

+0

@Pradeep一樣的,如果它存在,只有我會的日期設置爲今天的日期,而不是返回的日期的存在來自Table1。 – NicT 2014-10-19 15:54:44

回答

1
update table1 
    set table1.date = insull(table2.date, getdate()) 
    from table1 
    left jion table2 
    on table2.ID = table1.ID 
+0

謝謝,這正是我一直在尋找的! :) 你知道我應該閱讀的東西來刷新SQL語法嗎?我覺得沒有必要,我根本無法把頭圍繞在它身上。 再次,謝謝! – NicT 2014-10-19 16:19:50

+0

當我是Sql Server 6.5的時候,我學到了這麼多東西。從那時起我有了我們的文檔。 – Paparazzi 2014-10-19 16:36:05

1

試試這個

UPDATE A 
SET A.datecol= CASE 
        WHEN EXISTS (SELECT 1 
           FROM Table1 B 
           WHERE B.cola = A.cola) THEN c.Datecol 
        ELSE getdate() 
       END 
FROM Table2 A 
     JOIN Table1 C 
     ON a.cola = c.cola 
2

首先,你應該得到的表的差異。檢查以下內容:

set nocount on 
declare @t1 table (id int, datecolumn datetime) 
declare @t2 table (id int, datecolumn datetime, fk_on_t1 int) 

declare @diff table(t1_id int, t2_id int) 

insert into @diff(t1_id,t2_id) 
select 
t1.Id 
,t2.ID 
from @t1 t1 
full join @t2 t2 on t1.id = t2.fk_on_t1 

現在您可以瞭解哪些行存在一個或另一個表。您可以使用這樣的查詢,爲你的情況更新您的日期欄:

update t2 
set datecolumn = getdate() 
from @t2 t2 
inner join @diff d on d.t2_id = t2.ID 
where d.t2_id is not null 

通常情況下,你可以只是一個查詢,而不是我的兩項。檢查:

update t1 
set datecolumn = getdate() 
from @t1 t1 
full join @t2 t2 on t1.id = t2.fk_on_t1 
where t2.ID is not null 
相關問題