如何在使用另一个表生成的表中设置主键?

时间:2015-12-18 10:28:18

标签: sql-server

我使用以下代码生成新表,与另一个表的表相同,但问题是,以下脚本会复制所有数据,但不会将所需列作为主键,而在父表中则如此是主键。请指导我如何创建与父表中相同的列主键。

ALTER procedure [dbo].[c_temp1]
AS 
    IF EXISTS (SELECT * 
               FROM dbo.sysobjects 
               WHERE id = object_id(N'[dbo].[coil_temp1]') 
                 AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
       DROP TABLE [dbo].[coil_temp1]

    SELECT * 
    INTO coil_temp1 
    FROM coil

1 个答案:

答案 0 :(得分:0)

这将为您创建主键的副本。

ALTER procedure [dbo].[c_temp1]
AS 

BEGIN

SET NOCOUNT ON;

Declare @PrimaryColumns varchar(1000)
        ,@PimaryName varchar(255)
        ,@AddPrimaryKey varchar (1050)

IF EXISTS (SELECT   * 
           FROM     dbo.sysobjects 
           WHERE    id = object_id(N'[dbo].[coil_temp1]') 
                    AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
    DROP TABLE [dbo].[coil_temp1]

select  @PrimaryColumns = coalesce(@PrimaryColumns + ',', '') +  COLUMN_NAME
from    (SELECT dISTINCT T1.CONSTRAINT_NAME , T2.COLUMN_NAME
        from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS T1
                INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE T2
                ON T1.CONSTRAINT_NAME = T2.CONSTRAINT_NAME
        where   T1.table_name = 'coil'
                AND T1.CONSTRAINT_TYPE = 'PRIMARY KEY')t3

SELECT  @PimaryName = T1.CONSTRAINT_NAME 
from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS T1
where   T1.table_name = 'coil'
        AND T1.CONSTRAINT_TYPE = 'PRIMARY KEY'

SELECT  * 
INTO    coil_temp1 
FROM    coil 

Set     @AddPrimaryKey = 'ALTER TABLE coil_temp1 ADD CONSTRAINT '+ @PimaryName +'_coil_temp1 PRIMARY KEY ('+@PrimaryColumns+')'

Exec (@AddPrimaryKey)

END
GO