Why does Create Table create a weirdly named key for the primary key? - sql

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.

Related

Error contains no primary or candidate keys that match the referencing column

This is my first Table : Tours
CREATE TABLE [dbo].[Tours] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[TourId] INT NOT NULL,
[TCountry] NVARCHAR (50) NULL,
[TName] NVARCHAR (100) NULL,
CONSTRAINT [PK_Tours] PRIMARY KEY CLUSTERED ([TourId]),
CONSTRAINT [FK_Tours_ToTourDates] FOREIGN KEY ([TourId]) REFERENCES [TourDates]([TourId]));
and this is the next, Table:TourDates
CREATE TABLE [dbo].[TourDates] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[TourId] INT NOT NULL,
[TourStartDate] DATETIME NULL,
CONSTRAINT [PK_TourDates] PRIMARY KEY CLUSTERED ([Id] ASC));
for first table I have this Error :
SQL71516 :: The referenced table '[dbo].[TourDates]' contains no
primary or candidate keys that match the referencing column list in
the foreign key. If the referenced column is a computed column, it
should be persisted.
How can one define a Candidate key for TourId column in TourDates Table??
I believe that you should be doing something else than you are doing right now.
Tours table seems to hold every tour which should be in 1:N relationship with TourDates provided that I understand it correctly.
Thus, your FOREIGN KEY constraint should actually be declared on TourDates, not Tours table.
As to your issue (which I believe wouldn't if you switch those relationships to what they should be in my understanding) in such cases you would normally need to create a unique index on that column.
You can't reference a column which may contain several exact same values via foreign key constraint, thus the need for some sort of a unique key.
Edit after comment:
ALTER TABLE [dbo].[TourDates]
ADD CONSTRAINT FK_Tour_TourDates
FOREIGN KEY ([TourId]) REFERENCES [dbo].[Tours]([TourId]) ON DELETE CASCADE

CONSTRAINT to foreign keys to one table - causes error

I am starting to build something like system up to the just cooperate with suggestions coming into the database called ForslagOpslag.
Every time I try to update table with likes, you will see it with this one error:
Update cannot proceed due to validation errors. Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[ForslagOpslag]' contains no
primary or candidate keys that match the referencing column list in
the foreign key. If the referenced column is a computed column, it
should be persisted.
Here is how I built my ForslagOpslagLikes table:
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
);
Reason I have both fk_brugerid and getid is for sure me that the user can not vote / like more once!
The way I have built my ForslagOpslag table:
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
like this to be my like system do:
ForslagOpslagLikes -> fk_brugerid to ForslagOpslag -> fk_brugerid
ForslagOpslagLikes -> getid to ForslagOpslag -> id
Well - the error seems pretty clear: you're trying to estabslish a foreign key relationship to ForslagOpslag.fk_brugerid here:
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
but that column is NOT the primary key of that other table - and it's not a UNIQUE constraint either - so you cannot reference that column in a foreign key relationship.
But the column(s) that a foreign key references must be the primary key of that other table - or in SQL Server, it's good enough if there's a UNIQUE constraint on that column. You must ensure that the values you reference in FroslagOpslag only match a single column in that table - otherwise, you cannot establish a foreign key relationship
Try to remove the foreing key in your first table like this
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
);
Then you need to add the foreign key in the second table with the primary key with the first table
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslagLikes]([fk_brugerid])
);
You sound scandinavian, and Bruger means User (for all the non-scandinavians here).
What you appear to want is a Bruger (User) table, where fk_brugerid in ForslagOpslag is the user who created the record with opretdato being the creation date, and ForslagOpslagLikes is an association table of users who likes the ForslagOpslag with opretdato being the date they clicked on "Like".
CREATE TABLE [dbo].[Bruger]
(
[brugerid] INT IDENTITY (1, 1) NOT NULL,
...,
CONSTRAINT [PK_Bruger]
PRIMARY KEY CLUSTERED ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR(MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
CONSTRAINT [PK_ForslagOpslag]
PRIMARY KEY CLUSTERED ([Id]),
CONSTRAINT [FK_ForslagOpslag_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid]),
CONSTRAINT [FK_ForslagOpslagLikes_ForslagOpslag]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id])
);

How to make Primary Key in Sql Server Using Alter Statement?

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

In SQL does a Primary Key in a create table enforce uniqueness?

Im wondering if on a relational table I set the two values below as a PRIMARY KEY if that automatically makes the table know that all entries should be unique....
CREATE TABLE UserHasSecurity
(
userID int REFERENCES Users(userID) NOT NULL,
securityID int REFERENCES Security(securityID) NOT NULL,
PRIMARY KEY(userID,securityID)
)
or do I need to be more explicit like this...
CREATE TABLE UserHasSecurity
(
userID int REFERENCES Users(userID) NOT NULL,
securityID int REFERENCES Security(securityID) NOT NULL,
PRIMARY KEY(userID,securityID),
UNIQUE(userID,securityID)
)
You don't need UNIQUE here. PRIMARY KEY will make sure there is no duplicate (userID,securityID) pairs.
No, you don't need to specify UNIQUE in addition to PRIMARY KEY. A primary key by definition must be unique.
A PRIMARY KEY has to be unique, so you only need to declare as a primary key. The underlying index is unique by definition.
Creating Unique Indexes

could unique key ( not primary ) be a parent for declarative foreign key constraint

Naive question with the answer "No" , I believe, but still would like to ask.
Table_parent
pk_parent_surrogate
parent_natural_unique_key
Table_child
pk_child_surrogate
child_natural_NOT_unique
Is that true that the only possible declarative relationship among main database vendors is
pk_parent_surrogate ----------< pk_child_surrogate
and we can't have declarative constraint or foreign key in other words for pair
parent_natural_unique_key -------< child_natural_NOT_unique
My answer here is based on my MS SQL knowledge - although I believe the same answer is correct for ANSI standards as well, i'm not 100% sure...
YES - you CAN do this as long as you've got a unique constraint on the column in your parent table that you want to use as the anchor column for the key.
You can create a FOREIGN KEY constraint as part
of the table definition when you create a table.
If a table already exists, you can add a
FOREIGN KEY constraint, provided that the
FOREIGN KEY constraint is linked to an existing
PRIMARY KEY constraints or UNIQUE constraint in
another, or the same, table. A table can contain
multiple FOREIGN KEY constraints.
And as an example of this sort of key...
use tempdb
CREATE TABLE parent(
pk int identity primary key,
candidate_key int unique not null)
CREATE TABLE child(
pk int identity primary key,
join_key int references parent(candidate_key))
See here for more information.
Try code like this:
create table testunique (id int identity(1,1) primary key, otherid int)
go
create unique index ixOther on testunique(otherid)
go
create table testFK (id int identity(1,1) primary key, someid int)
go
alter table testFK add constraint fkTest foreign key (someid) references testunique(otherid)
Rob