2016-04-28 73 views
2

有如下表:SQL Server的更新,如果記錄不表B中發現

表名PLANS

字段名稱

Key EMP _ID 
Key PLAN_NUMBER 
STATUS 
FIELD1 
FIELD2 
FIELD3 
FIELD4 

表名PLANS_TEMP

Key EMP_ID 
Key PLAN_NUMBER 
STATUS 
FIELD1 
FIELD2 
FIELD3 
FIELD4 

想要在有數據表。

不想刪除的記錄,而不是要設置狀態=「我」如果PLANS_TEMP

  1. 不存在記錄,如果記錄不存在Office_Plan_temp要更新Office_Plan.Status ='我

喜歡的東西如下:

Update P 
Set status = ‘I’ 
Where emp_id and plan_number not exists in Plans_Temp table 

(我們必須匹配LOCATION_ID & PLAN_NUMBER)

  1. 如果記錄在Plans_Temp表中找到,但不在Plans表中,則要插入。

  2. 對於所有現有的記錄,想檢查field1,field2,field3和field4是否有任何變化,然後更新。

任何幫助將不勝感激。

+1

我認爲你需要'MERGE'在這種情況下。更多信息請訪問https://msdn.microsoft.com/en-us/library/bb510625.aspx – gofr1

回答

1

像這樣的東西可以幫助你:

MERGE PLANS as target 
USING PLANS_TEMP as source 
ON target.EMP_ID = source.EMP_ID AND target.PLAN_NUMBER = source.PLAN_NUMBER 
--If record doesn’t exists in Office_Plan_temp Wants to update Office_Plan.Status = ‘I’ 
WHEN NOT MATCHED BY SOURCE THEN 
    UPDATE SET [STATUS] = 'I' 
--If Record found in Plans_Temp table but not in Plans table, wants to insert. 
WHEN NOT MATCHED BY TARGET THEN 
    INSERT (EMP_ID, PLAN_NUMBER, [STATUS], FIELD1, FIELD2, FIELD3, FIELD4) 
    VALUES (source.EMP_ID, source.PLAN_NUMBER, source.[STATUS], source.FIELD1, source.FIELD2, source.FIELD3, source.FIELD4) 
--For all the existing records, (! HERE UPDATE WITHOUT ANY CHECKING wants to check if there’s any change in) field1, field2, field3 and field4 then update. 
WHEN MATCHED THEN 
    UPDATE SET target.FIELD1 = source.FIELD1, 
       target.FIELD2 = source.FIELD2, 
       target.FIELD3 = source.FIELD2, 
       target.FIELD4 = source.FIELD4; 
相關問題