简体   繁体   English

在SQL中使用唯一条目列创建表

[英]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. 我正在尝试使其达到最底线,以使“ Gebruikersnaam”列中的每个条目都是唯一的。 Is what I did right? 我做的对吗? What do you call this type of feature? 您如何称呼这种功能?

each entry in the "Gebruikersnaam" column is unique “ Gebruikersnaam”列中的每个条目都是唯一的

Yes it's right. 是的这是对的。 Essentially what you did is nothing but adding a UNIQUE CONSTRAINT to your column Gebruikersnaam . 本质上,您所做的不过是在您的专栏Gebruikersnaam添加UNIQUE CONSTRAINT 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. 我也将使用nvarchar代替varchar。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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