SQL SERVER 2008中的复合键 [英] Composite key in SQL SERVER 2008

查看:78
本文介绍了SQL SERVER 2008中的复合键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SQL Server Management Studio中创建了一个表。我把三列作为复合键。我注意到这些列采用重复值。但有时当我尝试插入重复值时,它会显示一条错误消息,指出发生了主键冲突。请解释一下为什么我们使用复合键以及它接受多少重复值。

解决方案

您只能有一个主键,但是您的主键可以有多个列密钥。

 CREATE TABLE userdata(
userid整数,
userdataid整数,
info char(200)
主键( userid,userdataid)
);


  CREATE   [dbo]。[Pri_Key](
[F_ID] [ int ] NOT NULL
[S_ID] [ int ] NOT NULL
[T_ID] [ int ] NOT NULL
CONSTRAINT [PK_Pri_Key] PRIMARY KEY CLUSTERED

[F_ID] ASC
[S_ID] ASC
[T_ID ] ASC
WITH (IGNORE_DUP_KEY = OFF ON [ PRIMARY ]
ON [ PRIMARY ]

insert Pri_Key 1 1 1
insert 进入 Pri_Key 1 1 2
insert into Pri_Key 1 1 3
insert into Pri_Key < span class =code-keyword> values ( 1 1 4



它将插入所有这些值,因为所有三个值都不相同,它将接受第一个重复作为第三列的2列是不同的,但如果所有三列都相同

  insert  < span class =code-keyword> into  Pri_Key  values  1  1  4 



这会给你一个错误...

消息 2627 ,等级 14 ,状态 1 ,行 2  
违规< span class =code-keyword> PRIMARY KEY 约束 ' PK_Pri_Key'插入重复密钥 对象' dbo.Pri_Key'



希望这会有所帮助..


I made a table in SQL server Management Studio. I made three columns as composite key. I noticed that these columns take duplicate value. But sometimes when I try to insert duplicate value it shows an error message that primary key violation is occured. Please explain me why we use composite key and how many duplicate value it accepts.

解决方案

You can only have one primary key, but you can have multiple columns in your primary key.

CREATE TABLE userdata (
  userid integer,
  userdataid integer,
  info char(200)
  primary key (userid, userdataid)
);


CREATE TABLE [dbo].[Pri_Key](
	[F_ID] [int] NOT NULL,
	[S_ID] [int] NOT NULL,
	[T_ID] [int] NOT NULL,
 CONSTRAINT [PK_Pri_Key] PRIMARY KEY CLUSTERED 
(
	[F_ID] ASC,
	[S_ID] ASC,
	[T_ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

insert into Pri_Key values (1,1,1)
insert into Pri_Key values (1,1,2)
insert into Pri_Key values (1,1,3)
insert into Pri_Key values (1,1,4)


it will insert all these values as all the three values are not same and it will accept duplicate for the first 2 columns as the third column is diffrent but if all the three are going to be same

insert into Pri_Key values (1,1,4)


this will gives you an error...

Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint 'PK_Pri_Key'. Cannot insert duplicate key in object 'dbo.Pri_Key'.


hope this helps..


这篇关于SQL SERVER 2008中的复合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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