一、创建自定义函数
ALTER FUNCTION [dbo].[ufn_GenerateUniqueID] ( @LengthNo int = 22, @RandomNum int = 0 ) RETURNS varchar(30) WITH EXEC AS CALLER AS BEGIN -- 返回值 DECLARE @RetValue VARCHAR(50) DECLARE @DatetimeString VARCHAR(14) DECLARE @randomString VARCHAR(50) Select @DatetimeString = CONVERT(VARCHAR(8), getdate(), 112) + replace(CONVERT(VARCHAR(8), getdate(), 114), ‘:‘,‘‘) SET @randomString = Right(Replicate(‘0‘,@LengthNo - 14) + CAST(@RandomNum AS VARCHAR(10)), @LengthNo - 14) SET @RetValue = @DatetimeString + @randomString --返回 RETURN @RetValue END
二、调用
--生成主键ID select dbo.ufn_GenerateUniqueID(22, floor(rand()*1e8))