Sql Server数据库中的主键和标识 [英] Primary key and Identity in Sql Server Database

查看:105
本文介绍了Sql Server数据库中的主键和标识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Sir / Medam,

i我在数据库中制作桌子时有点问题。

我的桌子是这样的。



CREATE TABLE [Customer]



CustomerId int Identity(1,1)PRIMARY KEY,

CustomerNumber int Not Null Identity(1,1)UNIQUE





可以在这样的2列表中给出标识。



给我回复.....

解决方案

你好,



首先你每个表只能有一个标识列,第二个我不知道为什么你需要在表中有两个标识列?因为即使你获得了两个标识列的成功,你将得到与这两个标题列相同的序列(例如。(1,1),(2,2,)....),这是无用的。那么这会带来什么好处呢?



看看复合键是否能够根据你的要求运作良好......或者告诉我们更多你想达到的目标这样我们就可以帮到你。



 CREATE TABLE [Customer] 

CustomerId int Identity (1,1),
CustomerNumber int非空,
PRIMARY KEY(CustomerId,CustomerNumber)


您可以这种方式分配主键。





创建表人员

P_Id int NOT NULL,
LastName varchar( 255 )NOT NULL ,
FirstName varchar( 255 ),
地址varchar( 255 ),
City varchar( 255 ),
CONSTRAINT pk_PersonID PRIMARY KEY(P_Id,LastName)


< blockquote>你不能在一个表中设置两个主键,但你可以在表中使用复合键,或者你可以使用唯一键来不允许重复数据。

如果这个没有解决你的问题解释你的问题简要说明。


Hello Sir/Medam,
i have a little problem while i make table in database.
My table like this.

CREATE TABLE [Customer]
(
CustomerId int Identity(1,1) PRIMARY KEY,
CustomerNumber int Not Null Identity(1,1) UNIQUE

)
iS that possible to gives identity in 2 column of table like this.

Give me reply.....

解决方案

Hello,

first you can have only one identity column per table, second i didn't get why you need two identity columns in your table?? As even if you get success to have two identity columns, you will get same sequence as a combination of these two (for eg. (1,1),(2,2,)....) which is useless i guess.. so what would be the benefit of that??

see if composite key works well according to your requirements... or tell us more that what you want to achieve so that we would be able to help you out.

CREATE TABLE [Customer]
(
CustomerId int Identity(1,1) ,
CustomerNumber int Not Null ,
PRIMARY KEY (CustomerId, CustomerNumber)
 
)


You can Assign Primary key in this manner.


CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)


You can not set two primary keys in one table but you can use composite key in your table or you can use unique key for not allow duplicate data.
If this one not solve your problem explain your question in brief with code.


这篇关于Sql Server数据库中的主键和标识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆