简体   繁体   English

创建SQL身份作为主键?

[英]Create SQL identity as primary key?

create table ImagenesUsuario
{
    idImagen int primary key not null IDENTITY
}

This doesn't work. 这行不通。 How can I do this? 我怎样才能做到这一点?

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: 通过显式使用“ constraint”关键字,可以为主键约束赋予特定的名称,而不是依赖于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 (ie, 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的搜索量和写入量的平衡超过通过其他索引对表进行聚类的好处)。

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] 

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: IDENTITYPRIMARY KEY NOT NULL ,因此,如果您愿意,可以忽略它。

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

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