I have forgot create a primary key for my table. Now I want to update the DocDay_Id column and make it the primary key. How can I do it?
My code is below.
I tried this syntax but it is not correct.
ALTER TABLE DoctorDays
ALTER COLUMN DocDay_Id int IDENTITY(1,1) PRIMARY KEY NOT NULL
Create table DoctorDays
(
DocDay_Id int IDENTITY(1,1) NOT NULL,
Doc_Id int FOREIGN KEY REFERENCES Doctor(Doc_Id) NOT NULL,
Day_Id int FOREIGN KEY REFERENCES Dayss(Day_Id) NOT NULL
)
To create a clustered primary key on an existing table:
ALTER TABLE DoctorDays ADD CONSTRAINT PK_DocDays
PRIMARY KEY CLUSTERED (DocDay_Id);
To create a non clustered primary key on an existing table:
ALTER TABLE DoctorDays ADD CONSTRAINT PK_DocDays
PRIMARY KEY NONCLUSTERED (DocDay_Id);
FIDDLE DEMO HERE
See the document in below link:
Alter Statement Documents
Related
I am facing a strange issue,
I have the following SQL table definition,
CREATE TABLE [dbo].[ParameterValue]
(
[ParameterValueID] INT NOT NULL IDENTITY(1, 1),
[ParameterID] INT NULL,
[FieldDefinitionID] INT NULL,
[ParameterValue] VARCHAR(2000) NULL,
[ParameterValueTypeID] SMALLINT NOT NULL DEFAULT 0,
)
GO
-- Constraints and Indexes
ALTER TABLE [dbo].[ParameterValue] ADD CONSTRAINT [Pk_ParameterValue_ParameterValueID] PRIMARY KEY CLUSTERED ([ParameterValueID])
GO
ALTER TABLE [dbo].[ParameterValue] ADD CONSTRAINT [FK_ParameterValue_Parameter] FOREIGN KEY ([ParameterID]) REFERENCES [Parameter]([ParameterID])
GO
ALTER TABLE [dbo].[ParameterValue] ADD CONSTRAINT [FK_ParameterValue_FieldDefinition] FOREIGN KEY ([FieldDefinitionID]) REFERENCES [FieldDefinition]([FieldDefinitionID])
GO
I noticed that in the table creation script, only the Primary key constraint is added; foreign key constraints are missing completely.
So the resultant table is created without the foreign keys.
What is the cause behind this?
Note: SQL Server Version --> 13.0.5103.6
I have no idea why I get an error when putting the foreing keys in MariaDB
I drop the full database if it exists
drop database if exists proveedoresCarrito;
create database proveedoresCarrito;
use proveedoresCarrito;
And now I'm going to create the tables
CREATE TABLE INVENTARIO (
NUMPIEZA CHAR(16) NOT NULL,
NUMBIN SMALLINT NOT NULL,
CANTDISPONIBLE SMALLINT,
FECHARECUENTO DATE,
PERIODORECUEN SMALLINT,
CANTAJUSTE SMALLINT,
CARTREORD SMALLINT,
PUNTOREORD SMALLINT);
CREATE TABLE LINPED (
NUMPEDIDO SMALLINT NOT NULL,
NUMLINEA SMALLINT NOT NULL,
NUMPIEZA CHAR(16),
PRECIOCOMPRA INTEGER,
CANTPEDIDA SMALLINT,
FECHARECEP DATE,
CANTRECIBIDA SMALLINT);
CREATE TABLE PEDIDO (
NUMPEDIDO SMALLINT NOT NULL,
NUMVEND SMALLINT,
FECHA DATE);
CREATE TABLE PIEZA (
NUMPIEZA CHAR(16) NOT NULL,
NOMPIEZA CHAR(30),
PRECIOVENT INTEGER);
CREATE TABLE PRECIOSUM (
NUMPIEZA CHAR(16) NOT NULL,
NUMVEND SMALLINT NOT NULL,
PRECIOUNIT INTEGER,
DIASSUM SMALLINT,
DESCUENTO SMALLINT);
CREATE TABLE VENDEDOR (
NUMVEND SMALLINT NOT NULL,
NOMVEND CHAR(30),
NOMBRECOMER CHAR(30),
TELEFONO CHAR(15),
CALLE CHAR(30),
CIUDAD CHAR(20),
PROVINCIA CHAR(20),
COD_POSTAL CHAR(5));
create table usuarios(
nombre SMALLINT NOT NULL,
pass CHAR(15)
);
I Set up the primary keys
ALTER TABLE INVENTARIO ADD CONSTRAINT CP_INVENTARIO PRIMARY KEY (NUMBIN);
ALTER TABLE LINPED ADD CONSTRAINT CP_LINPED PRIMARY KEY (NUMPEDIDO, NUMLINEA);
ALTER TABLE PEDIDO ADD CONSTRAINT CP_PEDIDO PRIMARY KEY (NUMPEDIDO);
ALTER TABLE PIEZA ADD CONSTRAINT CP_PIEZA PRIMARY KEY (NUMPIEZA);
ALTER TABLE PRECIOSUM ADD CONSTRAINT CP_PRECIOSUM PRIMARY KEY (NUMPIEZA, NUMVEND);
ALTER TABLE VENDEDOR ADD CONSTRAINT CP_VENDEDOR PRIMARY KEY (NUMVEND);
AND FINALLY i set up the foreign keys
ALTER TABLE INVENTARIO ADD CONSTRAINT CP_INVENTARIO PRIMARY KEY (NUMBIN);
ALTER TABLE LINPED ADD CONSTRAINT CP_LINPED PRIMARY KEY (NUMPEDIDO, NUMLINEA);
ALTER TABLE PEDIDO ADD CONSTRAINT CP_PEDIDO PRIMARY KEY (NUMPEDIDO);
ALTER TABLE PIEZA ADD CONSTRAINT CP_PIEZA PRIMARY KEY (NUMPIEZA);
ALTER TABLE PRECIOSUM ADD CONSTRAINT CP_PRECIOSUM PRIMARY KEY (NUMPIEZA, NUMVEND);
ALTER TABLE VENDEDOR ADD CONSTRAINT CP_VENDEDOR PRIMARY KEY (NUMVEND);
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_NOMBRE FOREIGN KEY (nombre) REFERENCES VENDEDOR(NUMVEND);
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_PASS FOREIGN KEY (pass) REFERENCES VENDEDOR(TELEFONO);
However, all the foreign keys work correctly except for the last two
when i run the sql script i get this error:
Error de SQL (1822): Failed to add the foreign key constaint. Missing index for constraint 'CA_VENDEDOR_USUARIOS_PASS' in the referenced table 'vendedor'
if I drop the last two foreign keys the error disappears
Anyone can give me a solution?
Look closely at your "set up the foreign keys" code. It creates primary keys again (except the two last lines).
Table usuarios seems to have no primary key.
ALTER TABLE usuarios ADD CONSTRAINT CP_usuarios PRIMARY KEY (nombre);
Delete the first 6 lines and keep only these
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_NOMBRE
FOREIGN KEY (nombre)
REFERENCES VENDEDOR(NUMVEND);
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_PASS
FOREIGN KEY (pass)
REFERENCES VENDEDOR(TELEFONO);
Also (and this is what generates your error), you are trying to add a foreign key to a column VENDEDOR(TELEFONO) which is not a primary key nor has a UNIQUE constraint.
According to Microsoft:
A foreign key constraint does not have to be linked only to a primary key constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
See: Create Foreign Key Relationships
Add this before creating the foreign keys:
ALTER TABLE VENDEDOR ADD CONSTRAINT UX_telefono UNIQUE (TELEFONO);
A foreign key has to reference always a primary key.
For you to reference the table VENDEDOR you should use the columns that compose its PK. In this example, NUMVEND.
If you need any suggestions on what to do, i'd have to know what are your intentions on this DB structure.
I want to switch the primary key away from my existing identity column
to a different column.
This is my table:
CREATE TABLE dbo.ParkingLot
(
ID int IDENTITY(1,1) PRIMARY KEY,
Address ???,
Status ???,
newID ???
);
I want to remove the primary key on the ID column and instead have newID be the primary key (this is a new column but it is already populated with values).
Drop primary Key constraint and Re-Add a new one
You have to drop the primary key constraint and add a new one
Drop primary key Constraint
-- Return the name of primary key.
SELECT name
FROM sys.key_constraints
WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) =
N'Tablename';
GO
-- Delete the primary key constraint.
ALTER TABLE Production.Tablename
DROP CONSTRAINT PK_Tablename;
GO
Add new primary key Constraint
ALTER TABLE Tablename ADD CONSTRAINT pk_NewPrimary PRIMARY KEY (Newid)
References
Delete Primary Keys
Change primary key column in SQL Server
When creating a basic table, the primary key name is auto generated. I would have thought dropping the constraint on the primary key column would have been enough.
CREATE TABLE TableExample
(
TEID Int NOT NULL IDENTITY(1,1) PRIMARY KEY
);
/** The only way to remove the constraint: **/
ALTER TABLE TableExample DROP CONSTRAINT PK__TableExa__B7FF674D29126160;
EDIT: How can I name this myself?
CREATE TABLE [dbo].[TableExample]
(
[TEID] [int] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_TableExample] PRIMARY KEY CLUSTERED ([TEID] ASC)
)
Or as a shorter alternative to Sam's response, if your primary key is on a single column (which is most often is), you could also use this:
CREATE TABLE [dbo].[TableExample]
(
[TEID] [int] IDENTITY(1,1) NOT NULL
CONSTRAINT [PK_TableExample] PRIMARY KEY CLUSTERED,
OtherColumn1 INT,
OtherColumn2 DATE,
.....
)
You can define the constraint and its name directly "inline" with the column. This works for other constraints, too (like default constraints or check constraints). This however does not work if your primary key, foreign key or other constraint is defined over more than one column.
I create a column as primary key , does this create indexes automatically ? or do i need to create indexes explicitly. i was under assumption that primary key also maintains indexes
In SQL Server creating a Primary key will create a Unique Clustered Index on that Column.
or more specifically from here
Note PRIMARY KEY constraints create
clustered indexes automatically if no
clustered index already exists on the
table and a nonclustered index is not
specified when you create the PRIMARY
KEY constraint.
This should clear out some air.
--creating a table without any primary key
CREATE table understanding_indexes
(P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
--
--checking for indexes
sp_helpindex understanding_indexes
OUTPUT
The object 'understanding_indexes' does not have any indexes, or you do not have permissions.
--ADDING A NOT NULL CONSTRAINT
ALTER TABLE UNDERSTANDING_INDEXES
ALTER COLUMN P_Id INTEGER
NOT NULL
--ADDING A PRIMARY KEY Constraint, can only be done on column which are not null.
ALTER TABLE UNDERSTANDING_INDEXES
ADD PRIMARY KEY (P_Id)
sp_helpindex understanding_indexes
OUTPUT
PK__understa__A3420A5702084FDA clustered, unique, primary key located on PRIMARY P_Id
Overall, As soon as you add a primary key constraint on a table, it automatically adds clustered indexes on the table.
This illustration is on SQL Server 2008 R2.