Hi, I'm having some weird behaviour with SQL. I have a method to check what the next ID will be (no multithreading or any chance of collisions there) but the problem is I'm getting the same ID twice the first time I add a new record.
This is my method:
First, I find it strange that the actual ID inserted is the (current) ID and NOT the (current + increment) ID. I've checked and the actual record is created with ID with value (current).Code:int result = -1; int current = 0; int increment = 0; string command; try { command = @"USE " + DBSettings.Name + Environment.NewLine; command += "SELECT IDENT_CURRENT('" + tableName + "') AS tinyint"; using (SqlCommand cmd = new SqlCommand(command, DBConnection)) current = (int)((decimal)cmd.ExecuteScalar()); command = @"USE " + DBSettings.Name + Environment.NewLine; command += "SELECT IDENT_INCR('" + tableName + "') AS tinyint"; using (SqlCommand cmd = new SqlCommand(command, DBConnection)) increment = (int)((decimal)cmd.ExecuteScalar()); result = current; //result = current + increment; exceptions = string.Empty; } catch (SqlException err) { exceptions = err.Message; } catch (InvalidOperationException err) { exceptions = err.Message; } Console.WriteLine("NextID for table '" + tableName + "': " + result + " (current: " + current + ", increment: " + increment + ")"); return result;
Second, I had the following results when adding records to a clean empty just created DB:
And this is not a matter of inserting records too fast or not allowing DB to update. I've done this "slow" to say it somehow and it happens anyway.Code:Console: NextID for table 'A': 1 Console: Adding element to table 'A' with ID 1 Console: NextID for table 'A': 1 Console: Adding element to table 'A' with ID 1 Console: NextID for table 'A': 2 Console: Adding element to table 'A' with ID 2 Console: NextID for table 'A': 3 Console: Adding element to table 'A' with ID 3
Tables are created with the following (relevant) fields:
If I reload every entry from DB I get the IDs ok. That is, PKs for every record are created ok. But my internal tracking (within my app) is offsetting my entries. I have a collection of elements and the first two have ID 1, which then messes up a later DB update since the element with (theoretical) ID 2 will overwrite ID 1.Code:string Command = @"IF NOT (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Product')) BEGIN CREATE TABLE Product ( ID tinyint NOT NULL PRIMARY KEY IDENTITY(1,1), IDPoint tinyint FOREIGN KEY REFERENCES Point(ID), ); END"; return RunCommand(Command);
Any ideas? Thanks!




Reply With Quote
