tsql - SQL Server: preventing manual insert into a column controlled by a sequence -


i have sequence object set on 1 of our databases increment of 1, using primary key 2 of our tables ensure uniqueness across them both. controlled via following constraint on tables:

add constraint seq_mysequence default (next value dbo.seq_sid) id; 

we want prevent user manually inserting data column, cannot find reliable method so. trigger seems obvious choice; after insert triggers execute after constraints fired , below not work:

create trigger blockinsert on mytable after insert    if (select id inserted) not null    begin        rollback end 

does have ideas?

if sequence main goal ensure uniqueness across 2 tables, consider using odd , identity columns on tables. example table have identity seed of 1 increment of 2 (odd) , table b have identity seed of 2 increment of 2 (even). if there chance identity_insert can used, have add additional check constraints ensure correct behavior. example use:

create table tablea  (     id int not null identity ( 1 , 2 ) constraint pk_odd primary key clustered ,     data varchar(10) )   -- check constraint ensures id odd alter table tablea add constraint ck_odd_id check ( id % 2 = 1 )   create table tableb (     id int not null identity ( 2 , 2 ) constraint pk_even primary key clustered ,     data varchar(10) )  -- check constraint ensures id alter table tableb add constraint ck_even_id check ( id % 2 = 0 ) 

this approach simplifies database design avoiding use of triggers , sequences. if uniqueness maybe required on more 2 tables sometime in future, avoid method together.


Comments