You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

sqlserver.sql 1.5 kB

4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /*
  2. ˵
  3. 1.SQL Serverһ÷д˽ű󣬽SQL Serverġɱ--ֵһ Fn_NextSnowId
  4. 2.ɵID = ʱ + WokerId +
  5. ʱ = ǰʱ뵥λ - 1582136402000
  6. WorkerId = {ֵ}
  7. = 5 2^SeqBigLength-1 ֮
  8. 3.÷
  9. 磺select dbo.Fn_NextSnowId(rand())
  10. */
  11. CREATE function dbo.Fn_NextSnowId
  12. (
  13. @RandomSeed float -- IDĺҪһڵʱϵͳ rand()
  14. )
  15. returns bigint
  16. as
  17. begin
  18. declare @CurrentTime bigint
  19. declare @TimeTick bigint
  20. declare @WorkerId int
  21. declare @WorkerIdBigLength int
  22. declare @SeqBigLength int
  23. -- Begin: ҪʼIJȷ @WorkerIdBigLength @SeqBigLength ֵӦóͬ
  24. set @WorkerId = 1 -- ֵ 2^@WorkerIdBigLength-1
  25. set @WorkerIdBigLength = 4 -- @WorkerIdBigLength+@SeqBigLengthҪ22
  26. set @SeqBigLength = 8
  27. -- End
  28. -- ǰʱ뵥λ
  29. set @CurrentTime = CONVERT(BIGINT,DATEDIFF(MI,'1970-01-01 00:00:00.000', GETUTCDATE())) * 60000 + DATEPART(S,GETUTCDATE()) * 1000 + DATEPART(MS, GETUTCDATE())
  30. -- õǰʱȥʱ䣬óIDʱ
  31. set @TimeTick=@CurrentTime-1582136402000
  32. -- ID
  33. -- ѩID = 52^SeqBigLength-1֮ (5 + round((POWER(2, @SeqBigLength)-1) * rand(), 0)
  34. return @TimeTick * POWER(2, @WorkerIdBigLength + @SeqBigLength) + @WorkerId * POWER(2, @SeqBigLength) + (5 + round((POWER(2, @SeqBigLength)-1) * @RandomSeed, 0))
  35. end
  36. GO