Here is a little test script to show you some interesting things about the identity column
1 - Most people use (1, 1).
However you can increment by five using (1, 5) which will leave gaps.
You can also start at (2000, 1) two thousand if you wanted to.
2 - Deleting all the records from a table will not reset the counter.
3 - Truncating the table will reset the counter to the base.
4 - Gaps can be due to deletes or conditions that prevent an insert.
A sample trigger is at the end to show if big money is not played, gaps will occur.
5 - Last but not least, you can start at the negative range of a type.
For an INT, start with -2147483648 and increment towards 2147483647, gives you twice the numbers.
However, if users see the id, you might not want this. Then use a BIGINT.
-- Just playing
use tempdb;
go
-- drop existing
if object_id('superbowl_pool') > 0
drop table superbowl_pool
go
-- create new
create table superbowl_pool
(
id int identity (1,1) primary key,
cash smallmoney
);
-- add data
declare @a int = 0;
while (@a < 100)
begin
insert into superbowl_pool (cash) values (rand(checksum(newid())) * 50);
set @a += 1;
end
go
-- show the data
select * from superbowl_pool;
Show the user that deletes do not reset counter.
-- delete does not reset the counter
delete from superbowl_pool;
go
-- Two records
insert into superbowl_pool (cash) values (rand(checksum(newid())) * 50);
insert into superbowl_pool (cash) values (rand(checksum(newid())) * 50);
go
-- Gaps in id column
delete from superbowl_pool where id = 102;
insert into superbowl_pool (cash) values (rand(checksum(newid())) * 50);
-- show the data
select * from superbowl_pool;
Show the user that a truncate resets the counter.
-- truncate table
truncate table superbowl_pool;
-- Two records
insert into superbowl_pool (cash) values (rand(checksum(newid())) * 50);
insert into superbowl_pool (cash) values (rand(checksum(newid())) * 50);
go
-- show the data
select * from superbowl_pool;
The users must play with $20 or more
-- create ins trigger
create trigger dbo.trg_big_money on dbo.superbowl_pool
FOR INSERT
AS
BEGIN
IF EXISTS (SELECT * FROM inserted where cash < 20)
ROLLBACK;
END