日期:2014-05-18 浏览次数:20786 次
create table aaa
( Id int identity(1,1),
No int default(isnull(scope_identity(),0)+1),
Name varchar(20)
)
insert into aaa(Name) values('a')
select * from aaa
/*
Id No Name
----------- ----------- --------------------
1 1 a
(1 row(s) affected)
*/
create table aaa
( Id int identity(1,1),
rno as id,
Name varchar(20)
)
insert into aaa(Name) values('a')
insert into aaa(Name) values('a')
insert into aaa(Name) values('a')
select * from aaa
drop table aaa
------解决方案--------------------
No列改为NOT NULL就可以了
create table aaa ( Id int identity(1,1), No int default(isnull(scope_identity(),0)+1), Name varchar(20) )
------解决方案--------------------
create table bbb
( Id int identity(1,1) primary key,
No int default(isnull(scope_identity(),0)+1) unique,
Name varchar(20)
)
insert into bbb(Name) values('a')
insert into bbb(Name) values('a')
select * from bbb
/*
Id No Name
----------- ----------- --------------------
1 1 a
2 2 a
(2 row(s) affected)
*/
------解决方案--------------------
No int default(isnull(scope_identity(),0)+1)
我电脑上试这种没有什么效果,是乱的,一会2,一会4,一会3。
测试因为是连续的,所以看不出来。
还是用小三的 no int as id 这个不错。
------解决方案--------------------
先创建表
CREATE TABLE ttt (
id int IDENTITY (1, 1) NOT NULL ,
noid int primary key NOT NULL
)
添加一个触发器,
CREATE TRIGGER tri_insert ON ttt
after INSERT
AS
begin
update ttt set noid=inserted.id from inserted where ttt.id=inserted.id
end
在插入数据后将id的值赋给noid列(插入数据默认给noid的值为0,规避主键不能为空),这样就可以了
并且支持update noid列
样例
insert into ttt(noid) values(0);
select id,noid from ttt
1 1
2 2
4 4
5 5
------解决方案--------------------