从单个CTE

时间:2017-03-09 19:07:03

标签: sql sql-server sql-server-2008

我尝试使用名为s4的cte查询cte,并根据结果插入或更新到另一个表eventslog。我无法在一个查询中执行此操作,并且需要先将数据插入临时表中。我想摆脱临时表部分的插入,只是直接插入或更新它。

我认为我遇到过多次调用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 个答案:

答案 0 :(得分:1)

您可以使用SQL 2008中提供的Merge命令,

这里有一个非常好的教程 http://www.made2mentor.com/2013/05/writing-t-sql-merge-statements-the-right-way/

答案 1 :(得分:0)

我最近在做类似的事情。我使用merge语句来处理使用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);