有两列一列是 YearID ,一列是ID 有记录如下:
2012 1
2012 2
2012 3
2012 4
2012 5
2012 6
sql server 自动的自动增长是用不成的,所以,只好先根据年份取出当年ID的最大值。然后在此基础上增加1
那么如果在取得并增加的这个过程中锁定数据库不让其他用户插入?
2012 1
2012 2
2012 3
2012 4
2012 5
2012 6
sql server 自动的自动增长是用不成的,所以,只好先根据年份取出当年ID的最大值。然后在此基础上增加1
那么如果在取得并增加的这个过程中锁定数据库不让其他用户插入?
go
if object_id('mytable') Is not null
Drop Table mytable
go
if object_id('fn_GetNextID') Is not null
Drop function fn_GetNextID
go
create function fn_GetNextID
(
@year int,
@rowID int
)
returns int
As
begin
return(select isnull(count(rowID),0)+1 from mytable where [year]=@year And rowID<@rowID)
end
Go
go
create table mytable
(
[year] int
,ID As dbo.fn_GetNextID([year],rowID)
,rowID int identity
,constraint PK_mytable primary key(rowID)
)
goinsert into mytable([year])
values(2011),(2011),(2011)
,(2012),(2012),(2013)
,(2013),(2012),(2013)insert into mytable([year])
values(2011),(2012),(2013)
goselect * from mytable/*
year ID rowID
-----------------------------
2011 1 1
2011 2 2
2011 3 3
2012 1 4
2012 2 5
2013 1 6
2013 2 7
2012 3 8
2013 3 9
2011 4 10
2012 4 11
2013 4 12
*/
选出最大ID后,如何锁定操作,不让其他用户继续插入数据?不然你选出最大ID后,用户又插入了一条信息,最大ID不是变化了吗
理論上是沒問題的,對於幷發環境我沒測試過。Insert操作的時候,就會生成排他鎖x鎖,也就是不让其他用户继续插入数据。