Evening all. I am fairly new to SQL
but have been doing quite a bit of fooling around. I am following a guide I found online to learn SQL
in 21 days and I am having a bit of trouble figuring out what the error I am receiving is causing.
I am trying to INSERT
data into an existing table. The Primary Key for this table is AddressID
. The data I am trying to enter is in the code below:
INSERT INTO [dbo].[Address]
(AddressID,Street,City,State,ZipCode)
VALUES
(1,'2400 Broadway','New York','NY',11201),
(2,'320 21st Street','Atlanta','GA',303),
(3,'439 Skyline Blvd','Seattle','WA',98101),
(4,'56 Park Avenue','Dallas','TX',75201);
GO
I keep getting this error:
Msg 2627, Level 14, State 1, Line 2 Violation of PRIMARY KEY constraint 'PK_Address'. Cannot insert duplicate key in object 'dbo.Address'. The duplicate key value is (1).
I have tried just about everything I can think of but I am unable to get my table updated. My column names at under the INSERT INTO
portion are correct and my VALUES are also correct. I did find that I can use a single INSERT
statement to get my data in the table. Originally I was using 4 separate statements.
What am I doing wrong?
What you doing wrong is:
AddressId
(1) in your tableAddress
table. Primary key should be unique. You cannot insert duplicate values in theprimary key
column.What you can probably do is:
update
the existing value andinsert
the new values. That means update the row withAddressId
1 and insert new rows with new AddressIds.It's better you let the
Sql Server
decide on your primary key value by creating `identity column'. You could create identity column while creating a table as follows:Please note that, if you have created a table with
Idenity column
, you do not need to supply any values duringinsert
operation because Sql Server implicitly creates and inserts that values for you.From the error message it is very clear that already
AddressID = 1
exist in the table since you have aprimary key
onAddressID
you cannot insert duplicate values.Try this query to insert into the table
If
addressid
columns hasidentity
property then remove theaddressid
column frominsert
column list andselect
list.In this case I think it's safe to let the database choose the primary key by not specifying it. There's probably already data in the table.
Primary Keys have to be unique. If AddressID is your primary key you cannot have two rows in your table that have the same AddressID number. Primary Keys are usually set automatically so you don't have to set them yourself.
Think of the Primary Key as a unique identifier for each row. The duplicate key error is telling you that you already have a row in your address table that has an AddressID value of 1. To avoid these errors you should set your AddressID column to IDENTITY and not worry about setting the value. Try inserting your records without setting the AddressID. Something like so: