Question

Let say I have this table

 Id(PK)     Country         Capital City
+--------+---------------+------------------+
+   1    +    USA        + Washington, D.C. +
+--------+---------------+------------------+
+   2    +   Japan       +  Tokyo           +
+--------+---------------+------------------+

What if I want to insert France-Paris. But I want that row to have Id = 1, USA Id = 2, then Japan Id = 3?

Is there a way to do that using SQL? What I'm about to do is to generate a Script where I'll do that manually. However, if there is a different way, I'd like to apply it.

Thanks for helping

Was it helpful?

Solution

Yes, but it isn't pretty if you get your values wrong. Use IDENTITY_INSERT

SET IDENTITY_INSERT dbo.Country ON
--Do your manipulation here.
INSERT INTO dbo.County(Id, country, [Capital City]) SELECT 1, 'France', 'Paris'
SET IDENTITY_INSERT dbo.Country OFF

BUT: You have an identity and a primary key and you need to shuffle values about so you would need to drop the ID column and re-create it since you cannot update an IDENTITY column. Given you may have other tables relying on this, this is likely to be more trouble than it's worth. If you're really desperate to have France at position 1 you will have to do quite a bit of work to disable FKs then copy the ID column to a new column, insert your value where you want it, make sure the numbers are sequential and finally re-create the identity and primary key and re-enable foreign keys.

As a side note, try and avoid spaces in object names.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top