How to insert row with explicit primary key

I have a small sql ce database and I want to restore some rows from an sql script. Everything works fine, except the newly added rows are given new primary keys, even though I explicitly state them in the insert statement. I can export a row with ID = 8 but when I insert it again, I get's a new ID, how can I insert a new row and force the database to give that row a specific ID ??? Otherwise I can't restore the database and give the imported rows the correct IDs.
ShaunDumasAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
BurniePConnect With a Mentor Commented:
You need to set identity_insert on first :

SET IDENTITY_INSERT TableName ON

INSERT INTO TableName (ID) VALUES (8)
0
 
8080_DiverCommented:
You should be aware that you can cause some serious issues if you insert duplicate primary keys.
0
 
Anthony PerkinsCommented:
>>if you insert duplicate primary keys. <<
I suspect you meant duplicate identity values.
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Fahad PathanTeam LeaderCommented:
if u r trying to insert duplicate values in primary key column then it is not possible, but you can insert duplicate values in identity column.
0
 
8080_DiverCommented:
@acperkins/@pathan_fahad,

reference the following quote from the author's original post:
except the newly added rows are given new primary keys, even though I explicitly state them in the insert

Even if the column is "just" an identity column and is not a PK, having a duplicate value in an "identity column" is going to mean that there will be a potential confusion with any use, whatsoever, of that identity column for purposes of identifying a given row.  (Sort of turns the concept of an "Identity column" into an oxymoron, don't you think?)

@ShaunDumas,
You can force the database to allow you to insert the value into the Identity column by the statements supplied in BurnieP's respons (#34234782); however, I would make sure that there are no rows with the same Identity value before inserting the rows.  This can be done by using something like the attached SQL.
INSERT INTO yourtable
(
 specify the columns
)
SELECT again specify the columns
FROM yourbackuptable B
LEFT OUTER JOIN yourtable Y
ON Y.identitycolumn = B.identitycolumn
WHERE Y.identitycolumn IS NULL;

Open in new window

0
 
ShaunDumasAuthor Commented:
Nice!
0
 
Anthony PerkinsCommented:
>>Sort of turns the concept of an "Identity column" into an oxymoron, don't you think<<
No doubt.  But you have to admit that the following is a tad impossible: "insert duplicate primary keys."
0
All Courses

From novice to tech pro — start learning today.