2017-03-09 55 views
1

我試圖使用稱爲s4的cte查詢cte,並根據結果插入或更新到另一個表eventslog。我無法在單個查詢中執行此操作,需要先將數據插入臨時表中。我想擺脫插入到臨時表部分,並直接插入或更新它。從單個CTE一起使用INSERT和/或UPDATE

我想我有多次調用該cte的問題。有沒有解決辦法?如何通過查詢單個cte插入或更新到表中?任何幫助最受讚賞。

SQL;

,ss4 
AS (SELECT DISTINCT h.groupid, 
        h.eventid, 
        Sum(h.vcheck) AS tot , 
        max(h.eventtime) as eventtime 
    FROM ss3 h 
    GROUP BY h.groupid, 
       h.eventid 
       ) 
INSERT INTO @glo 
      (eventtime, 
      eventid, 
      groupid, 
      vcheck) 
SELECT DISTINCT i.eventtime, 
       i.eventid, 
       i.groupid, 
       i.tot 
FROM ss4 i 


INSERT INTO eventslog 
      (eventtime, 
      eventid, 
      groupid) 
SELECT DISTINCT j.eventtime, 
       j.eventid, 
       j.groupid 
FROM @glo j 
WHERE  
    j.vcheck = 0 
    AND NOT EXISTS(SELECT eventid 
       FROM eventslog 
       WHERE eventid = j.eventid 
         AND groupid = j.groupid 
         AND clearedtime IS NULL) 


UPDATE k 
SET k.clearedtime = l.eventtime 
FROM eventslog k 
     RIGHT JOIN @glo l 
       ON k.groupid = l.groupid 
        AND k.eventid = l.eventid 
WHERE l.vcheck > 0 
     AND k.groupid = l.groupid 
+2

結合'CTE'用'MERGE' – lad2025

+0

謝謝.....我讀這個現在.....這是否鏈接幫助說明,你說了什麼? https://sqlsunday.com/2013/03/17/using-merge/ – arios

回答

0

我從事類似的東西我自己最近。我使用合併語句來處理使用CTE進行插入或更新。下面

例子:

;WITH cte AS 
(

    SELECT id, 
      name 
    FROM [TableA] 
) 

MERGE INTO [TableA] AS A 
    USING cte 
     ON cte.ID = A.id 

     WHEN MATCHED 
     THEN UPDATE 
     SET A.name = cte.name 

     WHEN NOT MATCHED 
     THEN INSERT 
    VALUES(cte.name);