Add Column as Primary Key

Asked

Viewed 2,242 times

2

I ran the following script:

CREATE TABLE [dbo].[horario](
    [Ano] [int] NOT NULL,
    [CodigoTurma] [varchar](5) NOT NULL,
    [Ordem] [int] NOT NULL,
    [Professor_Id] [int] NOT NULL,
    [Matriz_Semestre] [int] NOT NULL,
    [Matriz_Curso_Codigo] [varchar](5) NOT NULL,
    [Matriz_Disciplina_Codigo] [varchar](5) NOT NULL,
 CONSTRAINT [primary key1] PRIMARY KEY CLUSTERED 
(
    [Ano] ASC,
    [Professor_Id] ASC,
    [Matriz_Semestre] ASC,
    [Matriz_Curso_Codigo] ASC,
    [Matriz_Disciplina_Codigo] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

I cannot remove the created table, so to add a new column surround the following command:

ALTER TABLE horario ADD Dia [int] NOT NULL

The problem is that I need this new column to also be part of the set primary key. Can someone help me?

For some reason the bank was like this:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

1 answer

3


Just drop the primary key and create it again:

ALTER TABLE horario
DROP CONSTRAINT [primary key1]
GO

ALTER TABLE horario
ADD CONSTRAINT [primary key1] PRIMARY KEY CLUSTERED
(
    [Ano] ASC,
    [Professor_Id] ASC,
    [Matriz_Semestre] ASC,
    [Matriz_Curso_Codigo] ASC,
    [Matriz_Disciplina_Codigo] ASC,
    [Dia] ASC
)
GO

To check the primary key name, use:

SELECT * from 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab
WHERE 
    Tab.Table_Name = 'horario'
    AND Constraint_Type = 'PRIMARY KEY'
  • You as always being feral @Gypsy, thank you very much my friend. But unfortunately returned a error: 'key1' is not a constraint., but I don’t understand why...

  • In the DROP or in the ADD?

  • the Drop ......

  • Check the key name if it is key1 even.

  • Well, in the script is exactly key1 even, but there is some way to be checked in the bank itself with some command?

  • @Jedaiasrodrigues I updated the answer.

  • I updated the question...

  • @Jedaiasrodrigues The previous query only gave the name of the columns, so I put another query that may be more useful.

  • The result was CONSTRAINT_NAME = primary key1 updated the question...

  • I discovered, just use: [Primary key1] with brackets in the name!

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.