[英]Error when ALTER TABLE - Msg 102, Level 15, State 1
I'm using SQL Server and trying to change an existing table: 我正在使用SQL Server并尝试更改现有表:
ALTER TABLE [Users]
(
[User_ID] INT IDENTITY(1,1) PRIMARY KEY,
[UserName] [NVARCHAR](30) NOT NULL UNIQUE, -- the only change is "UNIQUE"
[UserEmail] [NVARCHAR](30) NOT NULL UNIQUE, -- the only change is "UNIQUE"
[Password] [NVARCHAR](30) NOT NULL,
)
And get this error: 并得到这个错误:
Msg 102, Level 15, State 1, Line 10
Msg 102,第15级,状态1,第10行
Incorrect syntax near '('.'('附近的语法不正确。
I'm changing the syntax each time but still get this error 我每次都在更改语法,但仍然会收到此错误
Msg 102, Level 15, State 1
消息102,第15级,状态1
What is the problem ? 问题是什么 ?
You just need to add a UNIQUE
constraint as 您只需要添加一个
UNIQUE
约束即可
ALTER TABLE [Users]
ADD CONSTRAINT U_UserName UNIQUE(UserName),
CONSTRAINT U_UserEmail UNIQUE(UserEmail);
Your syntax for ALTER TABLE
is completely wrong - if you just want to add UNIQUE
to the two columns in question - use this: 您的
ALTER TABLE
语法完全错误-如果您只想将UNIQUE
添加到有问题的两列中,请使用以下命令:
ALTER TABLE [Users]
ADD CONSTRAINT UQ_Users_UserName UNIQUE (UserName);
ALTER TABLE [Users]
ADD CONSTRAINT UQ_Users_UserEmail UNIQUE (UserEmail);
Read all about the ALTER TABLE
command on Docs@Microsoft 阅读有关Docs @ Microsoft 的
ALTER TABLE
命令的全部信息
Alter
are different with Create
Statement.. Alter
与Create
语句不同。
Definition : 定义 :
ALTER TABLE statement is used to add, delete, or modify columns in an existing table also used to add and drop various constraints on an existing table
ALTER TABLE语句用于添加,删除或修改现有表中的列,还用于在现有表上添加或删除各种约束
You can check here for demo it is works : DEMO
您可以在此处查看演示是否可行:
DEMO
Cannot add Unique Key constraint at column level. 无法在列级别添加唯一键约束。 Unique Key Constraint are defined at table level.
唯一键约束在表级别定义。
You may alter table to add Unique key in below ways. 您可以通过以下方式更改表以添加唯一键。
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n);
for eg 例如
ALTER TABLE Users
ADD CONSTRAINT Users_Unique UNIQUE (UserName, UserEmail);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.