看起來像一個意外的等待沒有纏着一個非常嚴格的交易發生即可獲得每日序列號。
編輯:強調Row_Number()
的計算取決於對所有行進行編號。
如何始終做INSERT
並使用結果生成顯示的每日ID?你是否看到有用的東西在這:
-- Create some sample data.
declare @Today as Date = GetDate()
declare @Stuff as Table (Id Int Identity, DateAdded Date)
insert into @Stuff (DateAdded) values
(DateAdd(day, -3, @Today)),
(DateAdd(day, -2, @Today)), (DateAdd(day, -2, @Today)),
(DateAdd(day, -1, @Today)), (DateAdd(day, -1, @Today)),
(@Today), (@Today)
-- Display the test data.
select Id, DateAdded,
Id - (select Min(Id) from @Stuff where DateAdded = S.DateAdded) as DailyId,
Row_Number() over (partition by DateAdded order by Id) as AlternativeDailyId,
Convert(VarChar(8), DateAdded, 112) + '-' +
Right('000000' + Cast(Id - (select Min(Id) from @Stuff where DateAdded = S.DateAdded) as VarChar(10)), 6) as DateId
from @Stuff as S
-- Add a row.
declare @NewRows as Table (Id Int, DateAdded Date)
insert into @Stuff
(DateAdded)
output inserted.Id, inserted.DateAdded into @NewRows
values (GetDate())
-- Display the new Id.
-- Note the the Row_Number() calculation only works when all rows are counted.
select N.Id, N.DateAdded,
N.Id - (select Min(Id) from @Stuff where DateAdded = N.DateAdded) as DailyId, -- NB: References @Stuff.
Row_Number() over (partition by N.DateAdded order by N.Id) as AlternativeDailyId,
Convert(VarChar(8), N.DateAdded, 112) + '-' +
Right('000000' + Cast(Id - (select Min(Id) from @Stuff where DateAdded = N.DateAdded) as VarChar(10)), 6) as DateId
from @NewRows as N
select *
from (
select S.Id, S.DateAdded,
S.Id - (select Min(Id) from @Stuff where DateAdded = S.DateAdded) as DailyId, -- NB: References @Stuff.
Row_Number() over (partition by S.DateAdded order by S.Id) as AlternativeDailyId,
Convert(VarChar(8), S.DateAdded, 112) + '-' +
Right('000000' + Cast(Id - (select Min(Id) from @Stuff where DateAdded = S.DateAdded) as VarChar(10)), 6) as DateId
from @Stuff as S
) as X
where Id in (select Id from @NewRows)
請注意,如果行被刪除會發生可怕的事情。日常的Ids會以驚心動魄的方式重新計算。