SQL 随机产生姓名

下面是我自己写的SQL随机产生一个或多个姓名,代码如下:

declare @firstNames varchar(max)	/* 保存名的集合 */
declare @lastNames varchar(max)		/* 保存姓的集合 */
set @firstNames = '芳,海,亮,红,君,军,俊,江,河,湖,波,杰,山,燕,阳,洋,涛,斌,彬,宾,微,伟,威,薇,刚,倩'	/* 必须只有一个字 */
set @lastNames = '刘,方,王,李,赵,孙,钱,胡,易,黄,温,丁,周,魏,陈,曾,涂'	/* 必须只有一个字 */
declare @lastNamesLength int
declare @firstNamesLength int
set @lastNamesLength = (LEN(@lastNames) - 1) / 2 + 1
set @firstNamesLength = (LEN(@firstNames) - 1) / 2 + 1

declare @firstNameRandom int
declare @lastNameRandom int

declare @resultFullNames varchar(max)
set @resultFullNames = ''

declare @i int
set @i = 1
while(@i <= 1000)
begin
	set @firstNameRandom = CEILING(rand()*@firstNamesLength)
	set @lastNameRandom = CEILING(rand()*@lastNamesLength)
	/*
		产生第 1 个字,对于的 Index 为 1,注意:这里的 Index 最小值为 1。
		产生第 2 个字,对于的 Index 为 3,
		产生第 3 个字,对于的 Index 为 5,
		...
	*/
	set @resultFullNames = @resultFullNames + ( SUBSTRING(@lastNames, @lastNameRandom * 2 - 1, 1) + SUBSTRING(@firstNames, @firstNameRandom * 2 - 1, 1) + ',' )
	set @i = @i + 1
end
print @resultFullNames

代码完毕,不过有一个缺点,目前不支持2个以上的姓氏和3个以上的名,随后我会继续更新,请期待...

原文地址:https://www.cnblogs.com/Music/p/1790782.html