使用CTE将SQL插入 [英] SQL insert into using CTE

查看:81
本文介绍了使用CTE将SQL插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于sql中的插入语句,我遇到了性能问题。我正在使用CTE从多个表中选择数据并插入其他表中。到昨天为止,一切都很好。 Select花费不到一分钟的时间来检索数据,并永久插入其中。有人可以帮我了解我在做什么错。非常感谢您的帮助。谢谢。

I am facing a performance issue due to "Insert into" statement in sql. I am using a CTE to select data from multiple tables and insert into other table. It was working just fine until yesterday. Select takes less than a minute to retrieve the data where as insert into taking forever. Can some one please help me in understanding what i am doing wrong. Any help is highly appreciated. Thanks.

这是我的代码:

我在SP中使用此查询。我正在尝试将220万条记录加载到150万条记录表中。

I am using this query in an SP. I am trying to load 220K records to 1.5M records table.

;with CTE_A
AS
(
      SELECT A1, A2,...           
      FROM dbo.A  with (nolock)
      WHERE A1 = <some condition>  
      GROUP BY a.A1,a.A2 , a.A3    
), CTE_C as
   (
       SELECT C1, C2,....                
       FROM dbo.B with (nolock)       
       WHERE a.C1 = <some condition>   
       GROUP BY a.c1,a.C2 , a.C3      
)
INSERT INTO [dbo].MainTable
    SELECT 
        A1, A2, A3 , C1, C2, C3       
    FROM 
        CTE_A ta with (nolock)
    LEFT OUTER JOIN 
        CTE_C tc with (nolock) ON ta.a1 = tc.a1 and ta.b1 = tc.b1 and ta.c1 = tc.c1 
    LEFT OUTER JOIN 
        othertable bs with (nolock) ON usd_bs.c = s.c   
                                        AND (A1 BETWEEN bs.a1 AND bs.a1)
                                        AND bs.c1 = 1                     


推荐答案

尝试此方法(用临时表代替cte),性能必须比您的任务高得多

try this method (temp table instead cte), perfomance must be much higher for your task

IF OBJECT_ID('Tempdb..#CTE_A') IS NOT NULL 
    DROP TABLE #CTE_A
IF OBJECT_ID('Tempdb..#CTE_C') IS NOT NULL 
    DROP TABLE #CTE_C
-------------------------------------------------------------
SELECT  A1 ,
        A2 ,...   
INTO    #CTE_A --data set into temp table
FROM    dbo.A WITH ( NOLOCK )
WHERE A1 = <some condition>  
GROUP BY a.A1 ,
        a.A2 ,
        a.A3
-------------------------------------------------------------
SELECT  C1 ,
        C2 ,....                
FROM    dbo.B WITH ( NOLOCK )       
INTO  #CTE_C --data set into temp table
WHERE a.C1 = <some condition>   
GROUP BY a.c1 ,
        a.C2 ,
        a.C3
INSERT  INTO [dbo].MainTable
        SELECT  A1 ,
                A2 ,
                A3 ,
                C1 ,
                C2 ,
                C3
        FROM    #CTE_A AS ta
                LEFT JOIN #CTE_C AS tc ON ta.a1 = tc.a1
                                          AND ta.b1 = tc.b1
                                          AND ta.c1 = tc.c1
                LEFT JOIN othertable AS bs ON usd_bs.c = s.c
                                              AND ( A1 BETWEEN bs.a1 AND bs.a1 )
                                              AND bs.c1 = 1

这篇关于使用CTE将SQL插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆