2016-02-03 35 views
-2

我們不能創造任何附加列 請記住這一點我要合併兩張表,沒有任何主鍵

這個腳本的整個目的是當數據匹配不要將數據合併到我的臨時表 不必做任何事情。 如果一些數據是否存在於#temp_cqm_class_template_xref而不是在cqm_class_template_xref_temp然後這些數據的必須從#temp_cqm_class_template_xref表

刪除,如果它是它必須被插入到#temp_cqm_class_template_xref表

IF OBJECT_ID('tempdb..#temp_cqm_class_template_xref') IS NOT NULL 
    DROP TABLE #temp_cqm_class_template_xref; 

CREATE TABLE #temp_cqm_class_template_xref (
    [template_name] [VARCHAR](30) NOT NULL 
    ,[measure_id] [INT] NOT NULL 
    ,[cqm_item_mstr_id] [INT] NOT NULL 
    ,[created_by] [INT] NOT NULL 
    ,[modified_by] [INT] NOT NULL 
    ,[create_timestamp] [DATETIME] NOT NULL 
    ,[modify_timestamp] [DATETIME] NOT NULL 
    ); 

MERGE INTO #temp_cqm_class_template_xref AS t 
USING cqm_class_template_xref_temp AS s 
    ON (
      t.template_name = s.template_name 
      AND t.measure_id = s.measure_id 
      AND t.cqm_item_mstr_id = s.cqm_item_mstr_id 
      ) 
WHEN NOT MATCHED 
    THEN 
     INSERT (
      template_name 
      ,measure_id 
      ,cqm_item_mstr_id 
      ,created_by 
      ,modified_by 
      ,create_timestamp 
      ,modify_timestamp 
      ) 
     VALUES (
      s.template_name 
      ,s.measure_id 
      ,s.cqm_item_mstr_id 
      ,s.created_by 
      ,s.modified_by 
      ,s.create_timestamp 
      ,s.modify_timestamp 
      ) 
WHEN NOT MATCHED BY target 
    THEN 
     DELETE; 
的其他方式

當我運行這個腳本,我得到以下錯誤:

Msg 10711, Level 15, State 1, Procedure ngdev_cqm_class_template_xref_bcp_upld, Line 88 An action of type 'INSERT' is not allowed in the 'WHEN MATCHED' clause of a MERGE statement

+2

這裏有問題嗎?你有什麼問題,錯誤?如果沒有ddl和基礎表的一些示例數據,這將會很有挑戰性。 –

+0

消息10711,級別15,狀態1,過程ngdev_cqm_class_template_xref_bcp_upld,行88 MERGE語句的'WHEN MATCHED'子句中不允許執行'INSERT'類型的操作。 –

+1

你說「*如果某些數據存在於#temp_cqm_class_template_xref中,而不是在cqm_class_template_xref_temp中,那麼這些數據必須從#temp_cqm_class_template_xref表中刪除,如果是另一種方式,它必須插入到#temp_cqm_class_template_xref表中*」最快/最安全/最可靠的方法是從'#temp_cqm_class_template_xref表中刪除',然後將'cqm_class_template_xref_temp'中的所有內容插入'#temp_cqm_class_template_xref表中'。 – RBarryYoung

回答

1

你可以嘗試類似左連接的東西,並找出相反表中的列爲空 ; 根據你的邏輯這可能對你有幫助

update t 
set t.template_name=null, 
t.measure_id = null, 
t.cqm_item_mstr_id = null 
#temp_cqm_class_template_xref t Left join cqm_class_template_xref_temp s on 
t.template_name = s.template_name 
      AND t.measure_id = s.measure_id 
      AND t.cqm_item_mstr_id = s.cqm_item_mstr_id 
delete from #temp_cqm_class_template_xref 
where measure_id is null and cqm_item_mstr_id is null and and template_name is null 
+1

感謝您的幫助.... 這是一個很好的接近 –

相關問題