是否有更好的方法从这个sql proc
获取每日序列# DECLARE @id int
UPDATE daily_identity
SET id = id + 1, @id = id + 1
WHERE day = CONVERT(VARCHAR(8), GETDATE(), 112)
IF @@ROWCOUNT = 0
INSERT INTO daily_identity values ( CONVERT(VARCHAR(8), GETDATE(), 112), 1 )
SELECT @id = 1
END IF
SELECT @id AS ‘id’
答案 0 :(得分:1)
看起来像一场事故正在等待,而没有非常严格的交易缠绕在它周围。
编辑:强调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 )
请注意,删除行会发生可怕的事情。每日的ID会以惊心动魄的方式重新计算。