简体   繁体   中英

Creating a table in SQL with column of unique entries

I have the following table:

Create table [dbo].[Medewerker]
(
    [Id] int PRIMARY KEY IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) UNIQUE NOT NULL
)

I'm trying to make it so that the bottom line makes it so that each entry in the "Gebruikersnaam" column is unique. Is what I did right? What do you call this type of feature?

each entry in the "Gebruikersnaam" column is unique

Yes it's right. Essentially what you did is nothing but adding a UNIQUE CONSTRAINT to your column Gebruikersnaam .

Per comment, yes it's better to name your constraint explicitly than let DB engine assign a default name implicitly like

Create table [dbo].[Medewerker]
(
    [Id] int PRIMARY KEY IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) NOT NULL,
    CONSTRAINT idx_unique_Gebruikersnaam UNIQUE(Gebruikersnaam) --Here
)

You have created an unique constraint, that is what it is called.
It is however always better to name your indexes and constraints, also the primary key you can give a name. Look at below examples.

You can create an unique index for an existing table like this

CREATE UNIQUE NONCLUSTERED INDEX idx_Gebruikersnaam
ON dbo.Medewerker(Gebruikersnaam)

in the table create it looks like this

Create table [dbo].[Medewerker]
(
    [Id] int IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) NOT NULL,

    constraint PK_MedewerkerId primary key (Id),
    constraint idx_Gebruikersnaam unique (Gebruikersnaam)        
)

Also I would use nvarchar in stead of varchar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM