I have never seen this before, the rows will be sequential but I have noticed that it skipped over a particular "ID".... 1 2 3 4 6 7 8... missing 5...
There are no transactions in the INSERT stored procedure so nothing to roll back
We do not allow the deletion of records.
What else can be the case?
Probably a failed insert due to some other unique constraint on the table or a foreign key reference in the table and you try to insert an invalid fk value.
The insert doesn't have to be in a transaction.
The identity value increments even on a failed insert.
Igor mentions an important point about identities and transactions. From the docs:
Failed statements and transactions can
change the current identity for a
table and create gaps in the identity
column values. The identity value is
never rolled back even though the
transaction that tried to insert the
value into the table is not committed.
For example, if an INSERT statement
fails because of an IGNORE_DUP_KEY
violation, the current identity value
for the table is still incremented.
Any way, identity counter does not restore your value (if you have executed with transaction or without it). The same behavior has oracle (sequences).
Identity is not transactional.
You may use your own primary key counter and control access to it.
Failed attempts generates an identity value even though it is not inserted into the data table. Then, this results to the lost of an identity (it's a shame I can no longer find the post where I have learned it!).
Related
I am using Sql server 2012(Amazon RDS). I have a table which has an identity column in it.At the beginning Identity column starts from 1,2 and so on and adding identity smoothly, but suddenly it jumps from 17018 to 27011. What could be the reason. Please assist.
thanks,
Sella
Restarting server instance may cause this.
See this
Any of these things can cause a jump in the identity column:
An insert into the table that is later rolled back
An error when inserting into the table (like unique constraint violation)
A delete from the table
Someone use IDENTITY INSERT ON to set a value for the identity column. If that value is bigger than the current value, the sequence will resume at that.
A server restart
In general, you shouldn't expect identity columns to increment by 1. Treat the value as random. The only difference between identity and a true random is that it's guaranteed to be increasing in value.
I got a Table with an Auto Increment Column which looks like:
ALTER TABLE SOMESCHEMA.SOMETABLE
ALTER COLUMN ID
SET DATA TYPE INTEGER GENERATED BY DEFAULT
SET INCREMENT BY 1
SET NO ORDER
SET NO CYCLE
SET MINVALUE 1
SET MAXVALUE 2147483647
SET NO CACHE;
As long as i let the DBMS generate the Ids everything works fine and I can get the generated Id via:
SELECT IDENTITY_VAL_LOCAL() FROM sysibm.sysdummy1
But sometimes i need to insert a row with an ID of my choice and there i get into trouble.
Lets say we got a single row in the table with ID 1.Now i insert a new row with a manually assigned id of 2. The next time i try to insert a new row without a preset ID i get an error SQL0803 "DUPLICATE KEY".
I assume the internal "NextId" field for that Auto-Increment Column doesnt update itself if the Id of a row is manually set.
So I tried reseting this field with:
ALTER TABLE SOMESCHEMA.SOMETABLE ALTER COLUMN ID RESTART WITH 3
But this causes a permanent Table lock, which i dont know how to unlock.
How can i get this "Mixed-Mode" ID-Column working? Is it possible to get it to work like MySQL where the DBMS automatically updates the "NextID" upon a manually-Id Insert? If not, how can I release that {insert swear-word here} lock that pops up if i try to reset the NextId?
SQL0913 isn't creating a lock - it is reporting that a lock exists. ALTER TABLE needs an exclusive lock on the table in order to reset the ID number. A table can be locked by another process having it open, or it can be locked by this process if there are uncommitted rows.
There is another reason the table is in use - soft close (or pseudo-close). For performance reasons, DB2 for i keeps cursors in memory so that they can be reused as efficiently as possible. So even if you say CLOSE CURSOR, DB2 keeps it in memory. These soft closed cursors can be closed by the command ALCOBJ OBJ((SOMSCHEMA/SOMETABLE *FILE *EXCL)) WAIT(1) CONFLICT(*RQSRLS) The CONFLICT(*RQSRLS) parameter tells DB2 to close all soft closed cursors.
So the root of the issue is that DB2 wants exclusive access to the table. Which is sort of a design question, because typically one doesn't manipulate the table's structure during the work day. It sounds as though this table is sometimes a parent and sometimes a child when it comes to ID numbers. If that is the case, may I suggest that you ALTER the table again?
I think the implementation might be better if you used a trigger rather than auto-increment. Fire the trigger on INSERT. If ID is supplied, do nothing. If ID is not supplied, SELECT MAX(ID)+1 and use that as the actual ID number you commit to the database.
ALTER TABLE table_name ALTER COLUMN column_name RESTART WITH 99999;
Fixed my issue. "99999" is the next ID to be used for example
With SQL, when inserting values into a Table from a SP, is it possible to get the value of the Primary Key before the values are added to the Table?
This is certainly possible, leveraging the power of relational databases. Assuming, like Martin Smith said, that you are using an autogenerated key, then you can use a transaction to do what you're looking for.
Here's the general idea:
Start a transaction.
Do the insertion.
Use the primary key to do whatever you need to do, including updated the inserted row to reflect the value.
Commit or rollback
By beginning a transaction before your insert, you can assure that no one else will be able to see the new rows until you commit your transaction. If the key is not to your liking, you can rollback the transaction, and no one else will know. If the key is adequate, you can modify the rows you have just inserted before committing.
Since you have a transaction, no one else can see the intermediate data you have inserted before you commit. Thus, you can update the rows that you have just inserted as if you have the primary key before your actual insert.
If you are using SQL Server the best way to do this is with your MERGE or INSERT command use the OUTPUT clause to get your key back. Even though this is not before the insert you can use the results of the OUTPUT to join back the results of your data to insert subsequent children records.
Also if you are using SQL server you can look at IDENT_CURRENT function which will return the current identity value of a table. If you are writing your SQL in a set based fashion the OUTPUT that I mention above works best for me.
Ever since I cleaned the data on the SQL Database I've been getting this issue, whereas on the unclean database the issue does not happen. When I run my stored procedure (huge procedure) it returns:
General SQL error. Cannot insert duplicate key row in object 'dbo.TitleClient' with unique index 'XAK1TitleClient'. Cannot insert the value NULL into column 'id_title', table 'Database.dbo.TitleCom'; column does not allow null, insert fails.
Is it possible that I deleted data from a table that causes this? Or is that impossible?
Does dbo.TitleClient have an identity column? You might need to run
DBCC CHECKIDENT('dbo.TitleClient')
I'm guessing that the first message
Cannot insert duplicate key row in
object 'dbo.TitleClient' with unique
index 'XAK1TitleClient'
is because the seed value is out of synch with the existing table values and the second error message
Cannot insert the value NULL into
column 'id_title', table
'Database.dbo.TitleCom' column does
not allow null, insert fails.
Comes from a failed attempt at inserting the result of scope_identity from the first statement.
How cleanly did you "clean" the data?
If some tables still have data, that might be causing a problem.
Especially if you have triggers resulting in further inserts.
For you to investigate further.
Take the body of your stored proc, and run it bit-by-bit.
Eventually, you'll get to the actual statement producing the error.
Of course if you aren't inserting into dbo.TitleClient at this point, then it's certainly a trigger causing problems.
Either way: Now you can easily check the data inserted earlier in your proc to figure out the root cause.
I had an unusual problem yesterday where I was suddenly unable to insert records into a table with an identity column.
A simple insert like this: INSERT INTO MyTable (Column1, Column2) VALUES ('text', 236764)
Started throwing a primary key constraint violation.
I ran DBCC CHECKIDENT on the table, and realized that SQL Server had stopped updating the last used value, so that when it was inserting it was incrementing using the old value and the new identity value usually already existed in the table, hence the violation errors.
Resolving the problem wasn't an issue, I just reseeded the table for the next highest sequence number, but I've never seen this happen before!
Does anyone have any idea what might cause SQL Server to stop updating identity properties, and where I might look for evidence? There is no replication or any triggers involved, it's just a plain old table.
EDIT: SQL Log Rescue would have been ideal, but it only works on SQL Server 2000. Is there a similar tool out there for SQL 2005 logs?
If someone has inserted to the table using SET IDENTITY_INSERT ON, someone could absolutely have entered in an invalid value for the table. That would be my first guess. You could use a log analyzer like SQL Log Rescue to go back in time through the transaction logs and see if you could find who the bad person was who messed up your data...
I think SET IDENTITY_INSERT ON reseeds the Identity.
From BOL
If the value inserted is larger than
the current identity value for the
table, SQL Server automatically uses
the new inserted value as the current
identity value.
The only way I could reproduce this issue was to manually set the seed too low with DBCC CHECKIDENT.