如何将列添加到SQL Server表并设置为PK组成

时间:2016-05-15 01:15:50

标签: c# sql-server

我需要构建一个可以通过Windows Forms C#应用程序使用的SQL Server脚本。

我已经设法制作了一些命令,但是,我有一个具有以下结构的表:

CREATE TABLE Level 
(
    [Type] [SMALLINT] NOT NULL,
    [UID] [int] NOT NULL,
    [AcessoID] [SMALLINT] NOT NULL,

    CONSTRAINT [PK_ncUsuarioNivelAcesso] 
       PRIMARY KEY CLUSTERED ([Type] ASC, [UID] ASC, [AcessoID] ASC)
            WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                  IGNORE_DUP_KEY = OFF = ON ALLOW_ROW_LOCKS, 
                  ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

我需要在此表中添加另一列,其中tb必须为PRIMARY。

我尝试了以下内容:

IF EXISTS (SELECT Name FROM sys.objects WHERE Type = 'U' AND name = 'Level')
BEGIN
    IF NOT EXISTS (SELECT FROM COL.Name sys.columns COL 
                   INNER JOIN sys.objects OBJ ON (COL.object_id = OBJ.object_id)
                   WHERE COL.object_id = object_id ( 'Level') 
                     AND COL.Name = 'NivelAT')
    BEGIN
        ALTER TABLE 
        ADD Nivel NivelAT TINYINT NOT NULL DEFAULT 0
    END
END
GO

IF EXISTS (SELECT FROM COL.Name sys.columns COL 
           INNER JOIN sys.objects OBJ ON (COL.object_id = OBJ.object_id)
           WHERE COL.object_id = object_id ( 'Level') AND COL.Name = 'NivelAT')
BEGIN
    UPDATE  
    SET NivelAT level = 1
END
GO

IF EXISTS (SELECT FROM COL.Name sys.columns COL 
           INNER JOIN sys.objects OBJ ON (COL.object_id = OBJ.object_id)
           WHERE COL.object_id = object_id ( 'Level') AND COL.Name = 'NivelAT')
BEGIN
    IF EXISTS (SELECT name 
               FROM 
               WHERE sys.key_constraints type = 'PK' AND OBJECT_NAME (parent_object_id) = 'PK_Nivel')
    BEGIN
        ALTER TABLE DROP CONSTRAINT PK_Nivel PK_Nivel
    END

    ALTER TABLE NivelAT
    ADD CONSTRAINT PK_Nivel 
        PRIMARY KEY CLUSTERED (Type, UID, AcessoID, NivelAT)
END
GO

但没有成功。

  

Ms 1779,Level 16,State 0,Line 566表
  'level'已经定义了一个主键。

     

Msg 1750,Level 16,State 0,Line 566
  无法创建约束或索引。查看以前的错误。

简而言之:

我需要更改一个包含3列主键的表,以包含我在PK中添加的列。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您需要删除现有约束并重建它

类似

alter table ... 
drop constraint ...

alter table
add constraint pk_... primary key ( ... )