Creating a Primary Key on a temp table - When?

后端 未结 9 673
一个人的身影
一个人的身影 2020-12-29 04:16

I have a stored procedure that is working with a large amount of data. I have that data being inserted in to a temp table. The overall flow of events is something like

9条回答
  •  灰色年华
    2020-12-29 05:01

    If the recovery model of your database is set to simple or bulk-logged, SELECT ... INTO ... UNION ALL may be the fastest solution. SELECT .. INTO is a bulk operation and bulk operations are minimally logged.

    eg:

    -- first, create the table
    SELECT ...
    INTO #TempTable
    FROM MyTable
    WHERE ...
    UNION ALL
    SELECT ...
    FROM MyTable2
    WHERE ...
    
    -- now, add a non-clustered primary key:
    -- this will *not* recreate the table in the background
    -- it will only create a separate index
    -- the table will remain stored as a heap
    ALTER TABLE #TempTable ADD PRIMARY KEY NONCLUSTERED (NonNullableKeyField)
    
    -- alternatively:
    -- this *will* recreate the table in the background
    -- and reorder the rows according to the primary key
    -- CLUSTERED key word is optional, primary keys are clustered by default
    ALTER TABLE #TempTable ADD PRIMARY KEY CLUSTERED (NonNullableKeyField) 
    

    Otherwise, Cade Roux had good advice re: before or after.

提交回复
热议问题