I've looked at a few SQL posts already but i'm unsure of their answers.. eg: SQL Unique Key Syntax
I want a Cities table... I want to define my country table whereby the Name column is unique... Using this as the base, how do I define a Unique column?
CREATE TABLE [dbo].[Cities]
(
[CityID] INT NOT NULL PRIMARY KEY,
[Name] NCHAR(100) NULL
)
You can create a constraint on the table to do this:
ALTER TABLE <tablename> ADD CONSTRAINT
<constraintname> UNIQUE NONCLUSTERED
(
<columnname>
)
You can add the unique keyword:
CREATE TABLE [dbo].[Cities]
(
[CityID] INT NOT NULL PRIMARY KEY,
[Name] NCHAR(100) NULL UNIQUE
);
There are alternative methods. You can add also add a unique index:
create unique index cities_name on dbo.Cities(Name);
Or do it with a unique constraint:
CREATE TABLE [dbo].[Cities]
(
[CityID] INT NOT NULL PRIMARY KEY,
[Name] NCHAR(100) NULL,
constraint unique_name unique(Name)
);
Related
I'm trying to create a table with 3 columns. The first column should be an identity column named DescriptionsID, the second column should be a foreign key column named ProductID, and the third column should be an xml column named Description. But, I'm receiving an error:
Foreign Key 'FK_ProductDescriptions_bacb18ce3aa67348e55d' references invalid table 'Product' and "Could not create constraint or index. See previous errors."
This is what I got:
CREATE TABLE ProductDescriptions (DescriptionsID int PRIMARY KEY NOT NULL,
ProductID varchar(25) NOT NULL,
FOREIGN KEY (ProductID) REFERENCES Product(ProductID),
Description text NULL) ;
References Product(ProductID) has the error/red underlining
When you create a Referential Constraint, You Need to make sure that the Table and the Column which you are referring already exists in the Database.
Also, the Datatype of Both Referring Column and the Referred Column Should Be the Same
Column 'Product.ProductId' is not the same data type as referencing column
'ProductDescriptions.ProductID' in the foreign key
So Create Product Table First, and set the Product Id as Primary Key
CREATE TABLE Product
(
ProductId INT IDENTITY(1,1) PRIMARY KEY,
ProductName VARCHAR(50)
)
CREATE TABLE ProductDescriptions
(
DescriptionsID int PRIMARY KEY NOT NULL,
ProductID INT NOT NULL
,FOREIGN KEY (ProductID) REFERENCES Product(ProductID),
[Description] text NULL
) ;
I have a question about this relation betweed SpelerTeam and Toernooi, i get a error, can someone help me with it all the other relations do work:
Msg 1776, Level 16, State 0, Line 2 There are no primary or candidate
keys in the referenced table 'SpelerTeam' that match the referencing
column list in the foreign key 'FK__Toernooi__team__1A14E395'. Msg
1750, Level 16, State 0, Line 2 Could not create constraint. See
previous errors.
CREATE TABLE dbo.LoginGegevens
(
Username varchar(25) NOT NULL,
Wachtwoord varchar(25) NOT NULL,
LoginDatum date NOT NULL,
)
CREATE TABLE dbo.NawGegevensKind
(
KindSpeler varchar(25) NOT NULL,
NawKind varchar(50) NOT NULL,
)
CREATE TABLE dbo.NawGegevensProfspeler
(
Profspeler varchar(25) NOT NULL,
NawProfspeler varchar(50) NOT NULL,
)
CREATE TABLE dbo.SpelerTeam
(
Team int NOT NULL,
Kindspeler varchar(25) NOT NULL,
Profspeler varchar(25) NOT NULL,
)
CREATE TABLE dbo.Toernooi
(
team int NOT NULL,
score int NOT NULL,
games int NOT NULL,
rondes int NOT NULL,
)
-- primary keys
ALTER TABLE LoginGegevens
ADD primary KEY (Username)
ALTER TABLE NawGegevensKind
ADD primary KEY (KindSpeler)
ALTER TABLE NawGegevensProfspeler
ADD primary KEY (ProfSpeler)
ALTER TABLE SpelerTeam
ADD primary KEY (Team,KindSpeler,ProfSpeler)
ALTER TABLE Toernooi
ADD primary KEY (Team,Rondes,Games)
-- relation
ALTER TABLE SpelerTeam
ADD FOREIGN KEY (Kindspeler)
REFERENCES NawGegevensKind(Kindspeler);
ALTER TABLE SpelerTeam
ADD FOREIGN KEY (Profspeler)
REFERENCES NawGegevensProfspeler(Profspeler);
ALTER TABLE Toernooi
ADD FOREIGN KEY (Team)
REFERENCES SpelerTeam(Team);
The Primary Key of SpelerTeam is Team,KindSpeler,ProfSpeler.
That means that any foreign key that references that table has to reference all three of those columns. You can't create a foreign key that uses only team.
You need an index on a colum so that it can be referenced as a foreign key efficiently. Add an index on SpelerTeam.Team and on all other columns with the same problem. Try CREATE INDEX IX_SpelerTeam_Team_Team ON SpelerTeam (Team);
Add below after all tables have been created:
CREATE UNIQUE NONCLUSTERED INDEX IX_SpelerTeam_Team
ON dbo.SpelerTeam (Team);
GO
As it was pointed in another answer you cannot reference to non unique column, to make column unique you can make this column primary key or create index for this column.
It is not enough that your "Team" column is part of composite key.
I want to insert my tables from my SQL Server Management Studio code with data via Visual Studio.
But it doesn't work. The ID of my table doesn't get a value automatically (but I have command it with identity(1,1)) and an error appears that it stands in conflict with a foreign-key-constraint.
create table [ProduktZahlungFENutzer]
(
ID int PRIMARY KEY IDENTITY(1,1) NOT NULL,
Endpreis decimal(3, 2)
);
CREATE TABLE [FHAngehörige]
(
FHAngehörigeID INT NOT NULL IDENTITY(1,1)
PRIMARY KEY Constraint fhA_feN
REFERENCES FENutzer(FENutzerID),
Name VARCHAR(50) NOT NULL,
Fachbereich INT NOT NULL,
Email VARCHAR(50) NOT NULL UNIQUE
)
CREATE TABLE [FENutzer]
(
FENutzerID INT IDENTITY(1,1) NOT NULL
PRIMARY KEY constraint t_nutzer
references ProduktZahlungFENutzer(ID),
Aktiv INT NOT NULL,
LetzterLogin datetime NOT NULL DEFAULT GETDATE(),
BENutzerID int NOT NULL
constraint FENutzer_BENutzer
foreign key references BENutzer(BENutzerID),
auth_id int not null
constraint FENutzer_auth
foreign key references auth2(id)
)
Please help
You have established a reference
FHAngehörigeID INT NOT NULL IDENTITY(1,1) PRIMARY KEY Constraint fhA_feN
REFERENCES FENutzer(FENutzerID),
This means that you need a record in your table FENutzer.FENutzerID that match FHAngehörigeID, in this case you cannot use IDENTITY
Your construction makes no sense - this way, you're creating two tables that depend on each other, at the primary key level - so you would have to have an existing entry in FENutzer in order to insert a new row into FHAngehörige, and this at the same time is only possible if you already have an existing row in FHAngehörige to insert the row in FEnutzer.....
You need to clean this up:
both tables need a primary key and the int identity(1,1) is a very good choice
one of the tables must reference the other, but with a normal foreign key attribute - not on the primary key.....
Since you've not given any indication as to which of the tables is the "main" table and which the "child/auxiliary" table, I'm just picking one over the other - so your table structure should be something like:
CREATE TABLE dbo.FHAngehoerige
(
FHAngehoerigeID INT NOT NULL IDENTITY(1,1)
CONSTRAINT PK_FHAngehoerige PRIMARY KEY CLUSTERED,
Name VARCHAR(50) NOT NULL,
Fachbereich INT NOT NULL,
Email VARCHAR(50) NOT NULL UNIQUE
)
CREATE TABLE dbo.FENutzer
(
-- define the PK for the table
FENutzerID INT IDENTITY(1,1) NOT NULL
CONSTRAINT PK_FENutzer PRIMARY KEY CLUSTERED,
-- define the **foreign key** to the main table
FHAngehoerigeID INT NOT NULL
CONSTRAINT FK_FENutzer_FHAngehoerige
FOREIGN KEY REFERENCES dbo.FHAngehoerige(FHAngehoerigeID),
Aktiv INT NOT NULL,
LetzterLogin datetime NOT NULL DEFAULT GETDATE(),
BENutzerID int NOT NULL
constraint FENutzer_BENutzer
foreign key references BENutzer(BENutzerID),
auth_id int not null
constraint FENutzer_auth
foreign key references auth2(id)
)
Also: I would strongly recommend (from my own personal, bad experience) to AVOID any special characters like umlauts or accents or anything like that in table and column names.....
I have a table with the following fields:
searchID ( I have set this as a primary key )
SearchText nvarchar(MAX)
.......
and so on
I want to make SearchText also as an additional primary field. How should this be done? Is that a good procedure to make two primary columns for a table?
It's impossible to have more than one primary key on one table and store unique values.
Your primary key must be as short as possible.
If you need to keep unique data in other column, you can create unique key on this column:
CREATE TABLE dbo.Table
(
SearchText nvarchar(MAX)NOT NULL,
CONSTRAINT AK_SearchText UNIQUE(SearchText)
);
Or with management studio:
You can create composite key as below
create table myTable
(
SearchId int not null,
SearchText nvharchar not null
)
GO
-- Add Constraint
ALTER TABLE myTable
ADD CONSTRAINT pk_myConstraint PRIMARY KEY (SearchId ,SearchText)
GO
I know I can specify it inline like this:
CREATE TABLE dbo.MyTable
(
Id INT NOT NULL CONSTRAINT PK_MyTable_Id PRIMARY KEY IDENTITY,
Created DATETIME NOT NULL CONSTRAINT DF_MyTable_Created DEFAULT GETDATE()
)
But I'd like to put all my constraints at the end of the table definition to keep them separate. I can't seem to find out how to name the column for the default constraint if I put it at the end of the table definition. I can do it with primary/foreign keys and unique constraints, but don't know how to specify the column name with a default constraint.
CREATE TABLE dbo.MyTable
(
Id INT NOT NULL IDENTITY,
Created DATETIME NOT NULL,
CONSTRAINT PK_MyTable_Id PRIMARY KEY( Id ),
CONSTRAINT DF_MyTable_Created DEFAULT GETDATE()
)
Do it separate with ALTER TABLE ADD..... syntax
like this
CREATE TABLE dbo.MyTable
(
Id INT NOT NULL IDENTITY,
Created DATETIME NOT NULL
)
GO
ALTER TABLE dbo.MyTable ADD CONSTRAINT PK_MyTable_Id PRIMARY KEY( Id ),
CONSTRAINT DF_MyTable_Created DEFAULT GETDATE() FOR Created
GO