最简单的方法是使用rand()
内置函数生成随机字符串(参考编号的中间部分)。不幸的是,SQL Server 不允许您创建非确定性函数,这基本上意味着您不能rand()
从自己的函数中调用。
一个简单(但有点难看)的解决方法是将随机字符串作为参数传递,因为您可以rand()
从存储过程中调用。听起来很混乱?这就是它的样子(假设你的随机字符串应该只包含大写字母):
create function UniqueRefNum (@r1 float, @r2 float, @r3 float, @r4 float)
returns char(14)
begin
-- Not sure if rand() might return 1.0
-- If it does, the conversion code below would produce a character that's not an
-- uppercase letter so let's avoid it just in case
if @r1 = 1.0 set @r1 = 0
if @r2 = 1.0 set @r2 = 0
if @r3 = 1.0 set @r3 = 0
if @r4 = 1.0 set @r4 = 0
declare @now datetime
set @now = getdate() -- or getutcdate()
declare @m char(2)
if month(@now) < 10
set @m = '0' + month(@now)
else
set @m = month(@now)
declare @d char(2)
if day(@now) < 10
set @d = '0' + day(@now)
else
set @d = day(@now)
return @m + @d + '-' +
char(65 + cast(@r1 * 26 as int)) +
char(65 + cast(@r2 * 26 as int)) +
char(65 + cast(@r3 * 26 as int)) +
char(65 + cast(@r4 * 26 as int)) +
'-' + cast(year(@now) as varchar)
end
然后,您从存储过程中调用该函数,如下所示:
declare @uniqueRef char(14)
set @uniqueRef = dbo.UniqueRefNum(rand(), rand(), rand(), rand())