DB2 和SQL Server自增列比較

zchbaby2000發表於2018-09-21

最近由於對SQL Server的自增列理解不夠好,導致了一個設計問題,做了2個小例子解釋一下

SQL Server的自增列
create table identitytest(
      id int identity(1,1),
      name varchar(20)
)
go
set IDENTITY_INSERT identitytest ON
go
insert into identitytest(id,name)values(1,'test1')
go
insert into identitytest(id,name)values(2,'test2')
go
set IDENTITY_INSERT identitytest OFF
go
insert into identitytest(name)values('test3')
go
set IDENTITY_INSERT identitytest ON
go
insert into identitytest(id,name)values(10000,'test4')
go
set IDENTITY_INSERT identitytest OFF
go
insert into identitytest(name)values('test5')

go
id      name
1       test1
2       test2
3       test3
10000   test4
10001   test5
(5 rows affected)
1>

SQL Server的自增列的值取決於表裡面的此列的當前的最大值。


create table identitytest(
id bigint not null generated by default as identity (start with 1,increment by 1),
name varchar(20)
);
insert into identitytest(id,name)values(1,'test1');
insert into identitytest(id,name)values(2,'test2');
insert into identitytest(name)values('test3');
insert into identitytest(id,name)values(10000,'test4');
insert into identitytest(name)values('test5');

db2 => select * from identitytest;

ID                   NAME                
-------------------- --------------------
                   1 test1               
                   2 test2               
                   1 test3               
               10000 test4               
                   2 test5               

  5 record(s) selected.

db2 =>

DB2的自增列,當你手工插入自增列的值的時候,DB2會無視你插入的值,DB2用自增列的定義產生值。




來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/725820/viewspace-2214688/,如需轉載,請註明出處,否則將追究法律責任。

相關文章