The value of primary key doesn't change - sql-server

I'm using visual studio 2010 an working on asp.net mvc3 project and sql server 2008. I have a table that the primary key of this table is int data type. I set Identity Specificatin "yes", Is Identity "yes", Identity Increment and Identity Seed "1". everything is OK when table is empty and data can be saved easily, But when I close visual studio, open it again and want to save data a break occured that shows the value of primary key is "1". (I deleted the data of database once, after this deletion the primary key of first row is 5 and other rows 6,7,...). What's the solution for this problem? your answer will be so helpfull. Thanks

There is no solution for *automatic gap removal": identity columns always have gaps for good reasons. For example, the deleted row is probably in some history or audit table and you don't wan to reuse it.
However, you can reset the column by using DBCC CHECKIDENT
Note the gotchas here: SQL server identity column values start at 0 instead of 1

Using Sequence type for the Primary Key may help...

Related

Identity Specification is making everything troublesome

So, my issue is that I am trying to make something that will easily load in Excel datasheets into a SQL database, but before this I have to try and make the identity specification cooperate with me.
The issue begins when I assign the primary key with identity specification being true, as then I get the error message "Cannot insert explicit value for identity column in table 'Priskod' when IDENTITY_INSERT is set to OFF."
However when I set that identity specification is false, then I get the error message "Violation of PRIMARY KEY constraint 'PK_dbo.Priskod'. Cannot insert duplicate key in object 'dbo.Priskod'. The duplicate key value is (0). The statement has been terminated."
Does anyone have any suggestions about how I can fix this?
It sound like you have an Excel spreadsheet that holds data that you want to import into a SQL Server table.
The issue is that you are trying to load it directly in to the source table and to enable this, you are disabling the IDENTITY column. This should ring alarm bells really, as SQL is right when it prevents you from inserting duplicate keys.
There are 2 options here:
The key values in Excel are true identity values that are unique, so you will only INSERT records they don't exist in the target table. This would probably be best achieved by importing to a staging/temp table first and the inserting where the ID doesn't exist. You may also want to perform an UPDATE on rows where the ID does exist.
The key values in Excel are NOT true identity values.
Either way, I think you should add a new column to your target table like: ExternalId, which can be duplicated if required or checked against to prevent duplicates. With both approaches, you should leave the IDENTITY insert as it is.
Got the system to work now.
I had to enter the information straight into the database instead of actually trying to upload the information into the database itself. So thanks everyone for your help and support. You are all super.

Empty table data and reset IDENTITY columns

I created a database in SQL Server with a couple of tables. I ran some tests and now am ready to deploy my solution, problem is, there is all sorts of data in the tables. I want to delete every row of all the tables created with my tests and put back the primary keys to zero. I tried delete which doesn't reset the primary keys index, and drop simply destroyed the table.
You can try TRUNCATE TABLE which deletes all rows and resets identity seeds. However you will have to execute in a certain order if you have foreign keys. In which case you will need to delete from the child tables first, or drop the constraints and re-add them.
Also note that if you are using IDENTITY you really shouldn't expect the numbers to mean anything, or to be generated forever without gaps. You shouldn't care whether it starts at 1 vs. 22 or 65 - can you explain why the identity values need to be reset?
From: http://www.howtogeek.com/howto/database/reset-identity-column-value-in-sql-server/
To set the value of the next ID to be 1, I can use this command:
DBCC CHECKIDENT (orders, RESEED, 0)

Making primary key and identity column after data has been loaded

I have quick question for you SQL gurus. I have existing tables without primary key column and Identity is not set. Now I am trying to modify those tables by making existing integer column as primary key and adding identity values for that column. My question is should I first copy all the records from the table to a temp table before making those changes . Do I loose all the previous records if I ran the T-SQL commnad to make primary key and add identity column on those tables. What are the approaches should I take such as
1) Create temp table to copy all the records from the table to be modified
2) Load all the records to the temptable
3) Make changes on the table schema
4) Finally load the records from the temp table to the original table.
Or
there are better ways that this? I really appreciate your help
Thanks
Tools>Options>Designers>Table and Database Designers
Uncheck "Prevent saving changes that require table re-creation"
[Edit] I've tried this with populated tables and I didn't lose data, but I don't really know much about this.
Hopefully you don't have too many records in the table. What happens if you use Management studio to change an existing field to identity is that it creates another table with the identity field set. it turns identity insert on and inserets the records from the original table, then turns identity insert off. Then it drops the old table and renames the table it just created. This can be quite a lengthy process if you have many records. If so I would script this out and then do it in a job that runs during the off hours because the table will be completely locked while you do this.
just do all of your changes in management studio, copy/paste the generated script into a file. DON'T SAVE CHANGES at this point. Look over and edit that script as necessary, it will probably do almost exactly what you are thinking (it will drop the original table and rename the temp one to the original's name), but handle all constraints and FKs as well.
If your existing integer column is unique and suitable, there should be no problem converting it to a PK.
Another alternative, if you don't want to use the existing column, you can add a new PK columns to the main table, populate it and seed it, then run update statements to update all other tables with new PK.
Whatever way you do it, make sure you do a back-up first!!
You can always add the IDENTITY column after you have finished copying your data around. You can also then reset the IDENTITY seed to the max integer + 1. That should solve your problems.
DBCC CHECKIDENT ('MyTable', RESEED, n)
Where n is the number you want the identity to start at.

MS-SQL Filling in Identity column values

I'm building an ASP.Net/MVC application using SQL 2008 Developer edition and a DB in Sql2005 compatibility mode. Using Entity Framework as DAL.
My problem is that I have a table where I'm using the integer identity column in a like an Invoice Number, that is, it always has to be unique and never reused. So using the GUID column type won't work without a substantial effort.
What I'm seeing is that the DB is filling in the gaps in the identity column. This will cause me long term problems. Is there a setting to disable this "filling in"
That sounds like something outside SQL server; SQL server does not "go back" and re-use gaps in identities unless the table's been reseeded, but even then it will blindly increment one-by-one and probably return a lot of duplicate key errors as it hits rows with existing values.
Are you sure the column is an identity? Is there anything else that might be re-assigning keys and/or turning on identity insert when creating rows?
SQL Server does not fill in the gaps of an identity field by default it will just keep going up in numbers as you insert rows.
It is possible to reset the identity back to 1 and therefore you may then see what you are describing.
Can I suggest you post some code / db structure that shows your problem and search for any code you may have that my perform an identity reseed.
Unless I am not understanding your issue correctly. If you create a primary key on your identity column, or a unique constraint, you can avoid the issue of duplicate values.
For example:
create table TableName
(
InvoiceID int identity(1,1) not null primary key
)

SQLSERVER: How to alter an existing table int primary key to become an identity column?

My database has a table with thousands of records. The primary key is an integer. There's a lot of foreign key constraints associated with this column.
I want to change this column to become an identity key. What's the best way to do it? I also need to send this update to our clients installations.
Bonus points for an answer that works in Sql Server 2000.
There's a great feature in SQL Server Management Studio that saved my day.
In SSMS go to Options -> Designers -> Table and Database Designers, check "Auto generate change scripts" and uncheck "Prevent saving changes that require table re-creation".
In object explorer, go to your table and select the column that will get the Identity specification. Right click and select modify. In the Column properties panel, expand the tree "Identity Specification" and change "(Is Identity)" to yes. Now on the upper left size, select the icon "Generate script". Pay attention to the warning messages.
Now you will have a generated script that will drop all your constraints, recreate the table with identity, and recreate the constraints. WOW!
I'll test it and post here my results.
Update: Everything worked fine. I forgot to say in the question that I need the script to reproduce the modification in our clients installations.
In Enterprise Manager, right click the table in table view, select design.
click the left hand side of the column (then, double click identity, in columns underneath, in column properties, turns it on, defaults to auto increment 1
There is no single "ALTER TABLE" DDL for changing an existing column to an identity column. You can only add a new identity column to an existing table.
This can be done in Enterprise Manager but you need to be aware that Sql server is creating a new table and copying you data across in the background. You may have some issues with this. Here is an article that explains this a bit more http://www.mssqltips.com/tip.asp?tip=1397
In your scenario i think you will need a combination of this script and something to disable and reenable your fk's.
If the column is an integer as a part of existing relationships then it is already unique. Therefore you do not have to worry about duplicates! That's one huge hassle avoided already.
You can either issue an ALTER TABLE command to change the column or you can do it with Enterprise Manager.

Resources