创建 SQL 身份作为主键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1355349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create SQL identity as primary key?
提问by Sergio Tapia
create table ImagenesUsuario
{
idImagen int primary key not null IDENTITY
}
This doesn't work. How can I do this?
这不起作用。我怎样才能做到这一点?
回答by richardtallent
Simple change to syntax is all that is needed:
只需对语法进行简单的更改即可:
create table ImagenesUsuario (
idImagen int not null identity(1,1) primary key
)
By explicitly using the "constraint" keyword, you can give the primary key constraint a particular name rather than depending on SQL Server to auto-assign a name:
通过显式使用“约束”关键字,您可以为主键约束指定一个特定名称,而不是依赖 SQL Server 来自动分配名称:
create table ImagenesUsuario (
idImagen int not null identity(1,1) constraint pk_ImagenesUsario primary key
)
Add the "CLUSTERED" keyword if that makes the most sense based on your use of the table (i.e., the balance of searches for a particular idImagen and amount of writing outweighs the benefits of clustering the table by some other index).
如果根据您对表的使用情况最有意义,请添加“CLUSTERED”关键字(即,搜索特定 idImagen 和写入量的平衡超过了通过其他索引对表进行集群的好处)。
回答by Mayo
This is similar to the scripts we generate on our team. Create the table first, then apply pk/fk and other constraints.
这类似于我们在团队中生成的脚本。先创建表,然后应用 pk/fk 和其他约束。
CREATE TABLE [dbo].[ImagenesUsuario] (
[idImagen] [int] IDENTITY (1, 1) NOT NULL
)
ALTER TABLE [dbo].[ImagenesUsuario] ADD
CONSTRAINT [PK_ImagenesUsuario] PRIMARY KEY CLUSTERED
(
[idImagen]
) ON [PRIMARY]
回答by Joe
If you're using T-SQL
, the only thing wrong with your code is that you used braces {}
instead of parentheses ()
.
如果您使用T-SQL
的是 ,那么您的代码唯一的错误是您使用了大括号{}
而不是圆括号()
。
PS: Both IDENTITY
and PRIMARY KEY
imply NOT NULL
, so you can omit that if you wish.
PS:两者IDENTITY
和PRIMARY KEY
暗示NOT NULL
,所以如果你愿意,你可以省略。