27,582
社区成员




--可以直接用给PK设置默认值,如:
--得到新编号的函数
CREATE FUNCTION f_NextBH()
RETURNS int
AS
BEGIN
RETURN(SELECT ISNULL(MAX(PK),0)+1 FROM tb WITH(XLOCK,PAGLOCK))
END
GO
--在表中应用函数
CREATE TABLE tb(
PK int PRIMARY KEY DEFAULT dbo.f_NextBH(),
col int)
--插入数据
INSERT tb(col) VALUES(1)
INSERT tb(col) VALUES(2)
INSERT tb(col) VALUES(3)
--显示结果
SELECT * FROM tb
if object_id('test')is not null drop table test
go
create table test(PK int,[Name] varchar(10))
insert Test select (select isnull(max(Pk)+1,1) from test),'A'
insert Test select (select isnull(max(Pk)+1,1) from test),'B'
insert Test select (select isnull(max(Pk)+1,1) from test),'C'
select * from test
/*
PK Name
----------- ----------
1 A
2 B
3 C*/
create trigger tb_insert
on tb
for insert
as
update tb set PK=PK+1