primary key not identity
Hey folks,
I'm trying to understand the rationale behind the way developers choose between setting the primary key as Identity=true vs false.
In the database I work with, many of the tables have a primary key that is set to not null as you'd expect, however, the "is identity" is set to false.
In the server logs when you look at the SQL statements which occur when a user (on the GUI) creates a new record, it looks like there are other statements happening before the insert query itself which asks for the Max(primarykey) in that table, then the results that are fetched are included in the insert query.
I'm wondering why they don't just set the primary key to: ID INT PRIMARY KEY IDENTITY
So for example, many of the tables are similar to this:
CREATE TABLE TEST_TABLE
(ID INT PRIMARY KEY NOT NULL, COL1 VARCHAR(10) NULL)
this looks like it would force the user to create their own primary key because the identity is not defined.
When I run the following insert and select:
INSERT INTO TEST_TABLE
(COL1)
VALUES
('TESTDATA')
SELECT * FROM TEST_TABLE
If I insert the above statements in SQL SERVER 2005, it shows an error because it says column ID can not be null. I get that, what I don't understand is why the developers would not create the table like this:
CREATE TABLE TEST_TABLE
(ID INT PRIMARY KEY IDENTITY NOT NULL, COL1 VARCHAR(10))
INSERT INTO TEST_TABLE
(COL1)
VALUES
('TESTDATA')
SELECT * FROM TEST_TABLE
This string of statements would not create an error because the ID is automatically created.
I'm just curious as it seems like not setting the ID to be the identity requires so many extra statements to occur in order to create the next consecutive number.
The database I work with does set unique primary keys, but like I said, it's through a series of preliminary select statements in the application itself that fetch the max value and then is put into the insert query.
Hope this makes sense!
Craig
Flam, February 14th, 2010 02:56 PM
Bookmarks