SQL Server Unique Constraint in Visual Studio SQL Designer

yfwxisqw  于 2023-06-21  发布在  其他
关注(0)|答案(2)|浏览(118)

I was looking at ways to make a newly added column a Unique but not primary column. I had a look at this W3School link . But Instead of following their approach I simply changed my table in the Visual Studio designer as.

CREATE TABLE [dbo].[Userpro] (
    [Id]                INT             NOT NULL IDENTITY,
    [Name]              NVARCHAR (50)   NULL,
    [Postcode]          NVARCHAR (4)    NULL,
    [Gender]            INT             NULL,
    [Blog]              NVARCHAR (MAX)  NULL,
    [FeedBack]          NVARCHAR (MAX)  NULL,
    [Username]          NVARCHAR (50)   NOT NULL Unique,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

Notice that I simply added "Unique"[Username] NVARCHAR (50) NOT NULL Unique . I am unsure if this has the same effect or should I go back and just use the script in the link.

ffscu2ro

ffscu2ro1#

That is perfect.

Adding UNIQUE will have the effect you describe. It is also explained in the link you provide.

wlwcrazw

wlwcrazw2#

If you want to specify the name for the unique constraint, then instead of adding the unique keyword to your column definition, you can append the full constraint definition to the CREATE statement.

The design view will automatically update and you will see Check_unique_username listed in the "Keys" section. You can also add it manually to the keys section by right-clicking and choosing "add new" > "unique key" - then use the properties panel to specify the name and column.

CREATE TABLE [dbo].[Userpro] (
    [Id]                INT             NOT NULL IDENTITY,
    [Name]              NVARCHAR (50)   NULL,
    [Postcode]          NVARCHAR (4)    NULL,
    [Gender]            INT             NULL,
    [Blog]              NVARCHAR (MAX)  NULL,
    [FeedBack]          NVARCHAR (MAX)  NULL,
    [Username]          NVARCHAR (50)   NOT NULL,
    CONSTRAINT          [Check_unique_username] UNIQUE ([Username]) -- <-- This line
PRIMARY KEY CLUSTERED ([Id] ASC)
);

相关问题