Click here to Skip to main content
15,905,682 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted

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)
);
 
Share this answer
 
Comments
Sumon562 19-May-13 1:38am    
actually My question was about composite key. If I have multiple columns in my primary key then Are they contain duplicate value. I know that primary key does not allow any duplicate key. I will be regretful if you explain.
SQL
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
SQL
insert into Pri_Key values (1,1,4)

this will gives you an error...
SQL
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..
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900