How to update the index value in SQL Server 2008 - sql

PFB my table structure
App id name
----- ------
1 Agile
4 sdlc
While entering data in above tables I wrongly entered some data twice. The index values has been changed to 4 instead of 2.
But I need the below index order
App id name
----- ------
1 Agile
2 sdlc

If you are using [App ID] in a UI and are concerned that users will highlight gaps in the values between records, then you shouldn't be using an identity column in this way. It's probably best you rethink your design and what you are trying to achieve. You could use an int column, or even a varchar, that you control yourself while using a primary key constraint.

Related

SQL server, is it possible to selectively over-write a computed column, or an IDENTITY int column

I'm in the process of migrating data to an SQL server database, ideally going foward I want to use the tables in this database to generate unique identities for the data being recorded in them, however the existing data comes with unique identities already.
I'd like to set up a table that looks like this
entry_num (PK)
component (FK)
long_id (Unique) - computed from combining row_num and component
1
THING1
THING1_1
2
THING2
THING2_2
3
THING1
THING2_3
I would like to be able to insert my existing data into the table by including it's existing id in the long_id column, and for future entries calculate the column automatically.
So my original inserted data might look like this:
entry_num (PK)
component (FK)
long_id (Unique) - computed from combining row_num and component
1
THING2
THING2_50
2
THING3
THING3_90
3
THING4
THING4_11
Alternatively could I manually specify the entry_num to match the identities?
I was planning on using
CREATE TABLE table_name (entry_num int IDENTITY...);
to auto increment this column, but is there another way that allows me to manually alter the identities of specific rows without violating the auto incrementing ability?

Entering data at a specific ID where as Auto Increment is ON (i.e Identity =TRUE)

how to insert value at a specific index in id Column where as Id Field is auto increment
for Example in may case say columns are ID and Name
ID Name
========================================
2 Austin
3 Peter
4 Albness
22 Sidhu
23 deepika
24 Shahrukh
Where Id is Auto incremented here in my case I have deleted the Id 1,4,5,6 to onward 21 and now I want to add the new name at Id=1 remember again Id is auto_increment (i.e Identity=TRUE in the property )
How do I Accomplish it
For all use cases I can think of, just leaving the gaps seems to be the simpler and safer solution. End users should not see these IDs, and DBAs should be OK with it.
If it's such a big deal, I'd still rather have a DBA manually run a "cleanup" script in a maintenance window than add complexity to production code.
To insert ID value on a table just do that
SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON | OFF }
Example your table name is People it should be
INSERT INTO People(ID,NAME) VALUES(3,'Felicio')
PS: to insert indentity value you also need to explicity the columns names and order as in previous example.
Id is either surrogate or natural key.
If it's surrogate, it doesn't have a meaning, and therefore gaps don't matter.
If it's natural, it shouldn't have been auto-increment in the first place.

Filling the gaps in values of IDENTITY column

I have a table with an IDENTITY column
[Id] int IDENTITY(1, 1) NOT NULL
After some rows beeing added/removed I end with gaps in Id values:
Id Name
---------
1 Tom
2 Bill
4 Kate
Is there an easy way to compress the values to
Id Name
---------
1 Tom
2 Bill
3 Kate
?
I would strongly recommend that you leave the identity values as they are.
if this ID column is used as a foreign key on another table, changing them will get complicated very quickly.
if there is some business logic where they must be sequential then add a new column ID_Display where you can update them using ROW_NUMBER() and keep them pretty for the end user. I never let end users see and/or dictate how I create/populate/store the data, and if they are bothering you about the IDs then show them some other data that looks like an ID but is not a FK or PK.
I think it's pretty easy to create a 2nd table with the same schema, import all the data (except for the identity column of course; let the 2nd table start renumbering) from the first table, drop the first table and rename the 2nd to the original name.
Easiness may be in question if you'd have a ton of FK relationships to rebuild with other tables etc.
Well as far as I know the only way you can is manually update the values by turning Identity insert on..but you should really avoid doning such a thing in first place..also if you truncate the table it will not have those gaps.
I cannot control the part which requires ID columns to be in sequence.
This sounds like there is program logic which assumes there are no gaps--correct?
I need this to keep two different databases in sync.
It's still not clear what you mean. If the actual values in the IDENTITY column are not meaningful (not used as foreign keys by other tables), you can just do this:
DELETE FROM db1.table
SELECT col1, col2, col3 /* leave out the IDENTITY column */
INTO db1.table FROM db2.table

Change all primary keys in access table to new numbers

I have an access table with an automatic primary key, a date, and other data. The first record starts at 36, due to deleted records. I want to change all the primary keys so they begin at 1 and increment, ordered by the date. Whats the best way to do this?
I want to change the table from this:
| TestID | Date | Data |
| 36 | 12/02/09 | .54 |
| 37 | 12/04/09 | .52 |
To this:
| TestID | Date | Data |
| 1 | 12/02/09 | .54 |
| 2 | 12/04/09 | .52 |
EDIT: Thanks for the input and those who answered. I think some were reading a little too much into my question, which is okay because it still adds to my learning and thinking process. The purpose of my question was two fold: 1) It would simply be nicer for me to have the PK match with the order of my data's dates and 2) to learn if something like this was possible for later use. Such as, if I want to add a new column to the table which numbers the tests, labels the type of test, etc. I am trying to learn a lot at once right now so I get a little confused where to start sometimes. I am building .NET apps and trying to learn SQL and database management and it is sometimes confusing finding the right info with the different RDMS's and ways to interact with them.
Following from MikeW, you can use the following SQL command to copy the data from the old to the new table:
INSERT
TestID, Date, Data
INTO
NewTable
SELECT
TestID, Date, Data
FROM
OldTable;
The new TestID will start from 1 if you use an AutoIncrement field.
I would create a new table, with autoincrement.
Then select all the existing data into it, ordering by date. That will result in the IDs being recreated from "1".
Then you could drop the original table, and rename the new one.
Assuming no foreign keys - if so you'd have to drop and recreate those too.
An Autonumber used as a surrogate primary keys is not data, but metadata used to do nothing but connect records in related tables. If you need to control the values in that field, then it's data, and you can't use an Autonumber, but have to roll your own autoincrement routine. You might want to look at this thread for a starting point, but code for this for use in Access is available everywhere Access programmers congregate on the Net.
I agree that the value of the auto-generated IDENTITY values should have no meaning, even for the coder, but for education purposes, here's how to reseed the IDENTITY using ADO:
ACC2000: Cannot Change Default Seed and Increment Value in UI
Note the article as out of date because it says, "there are no options available in the user interface (UI) for you to make this change." In later version the Access, the SQL DLL could be executed when in ANSI-92 Query Mode e.g. something like this:
ALTER TABLE MyTable ALTER TestID INTEGER IDENTITY (1, 1) NOT NULL;

SQL Table Design - Identity Columns

SQL Server 2008 Database Question.
I have 2 tables, for arguments sake called Customers and Users where a single Customer can have 1 to n Users. The Customers table generates a CustomerId which is a seeded identity with a +1 increment on it. What I'm after in the Users table is a compound key comprising the CustomerId and a sequence number such that in all cases, the first user has a sequence of 1 and subsequent users are added at x+1.
So the table looks like this...
CustomerId (PK, FK)
UserId (PK)
Name
...and if for example, Customer 485 had three customers the data would look like...
CustomerId | UserId | Name
----------
485 | 1 | John
485 | 2 | Mark
485 | 3 | Luke
I appreciate that I can manually add the 1,2,3,...,n entry for UserId however I would like to get this to happen automatically on row insert in SQL, so that in the example shown I could effectively insert rows with the CustomerId and the Name with SQL Server protecting the Identity etc. Is there a way to do this through the database design itself - when I set UserId as an identity it runs 1 to infinity across all customers which isn't what I am looking for - have I got a setting wrong somewhere, or is this not an option?
Hope that makes sense - thanks for your help
I can think of no automatic way to do this without implementing a custom Stored Procedure that inserted the rows and checked to increment the Id appropriately, althouh others with more knowledge may have a better idea.
However, this smells to me of naturalising a surrogate key - which is not always a good idea.
More info here:
http://www.agiledata.org/essays/keys.html
That's not really an option with a regular identity column, but you could set up an insert trigger to auto populate the user id though.
The naive way to do this would be to have the trigger select the max user id from the users table for the customer id on the inserted record, then add one to that. However, you'll run into concurrency problems there if more than one person is creating a user record at the same time.
A better solution would be to have a NextUserID column on the customers table. In your trigger you would:
Start a transaction.
Increment the NextUserID for the customer (locking the row).
Select the updated next user id.
use that for the new User record.
commit the transaction.
This should ensure that simultaneous additions of users don't result in the same user id being used more than once.
All that said, I would recommend that you just don't do it. It's more trouble than it's worth and just smells like a bad idea to begin with.
So you want a generated user_id field that increments within the confines of a customer_id.
I can't think of one database where that concept exists.
You could implement it with a trigger. But my question is: WHY?
Surrogate keys are supposed to not have any kind of meaning. Why would you try to make a key that, simultaneously, is the surrogate and implies order?
My suggestions:
Create a date_created field, defaulting to getDate(). That will allow you to know the order (time based) in which each user_id was created.
Create an ordinal field - which can be updated by a trigger, to support that order.
Hope that helps.