且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Sql Server数据库中的主键和标识

更新时间:2023-02-08 15:41:59

你好,



首先你每个表只能有一个标识列,第二个我不知道为什么你需要在表中有两个标识列?因为即使你获得了两个标识列的成功,你将得到与这两个标题列相同的序列(例如。(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)


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

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


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.