1、业务场景
实际业务开发需要模拟用户11位手机号,数据库如何快速生成随机不重复号码?
2、知识前提
11位手机号码参考百度说明:
3、实现方案
SQLServer编写函数,生成随机11位测试用手机号,只考虑MAC段,前三位符合手机号码段规范。
函数GetRandPhoneNum入参说明:
@operator表示号段;
@seed表示随机种子,固定newid()
具体sql语句:
--sqlserver生成11位测试用随机手机号GetRandPhoneNum
if exists(select 1 from sysobjects where id=OBJECT_ID('GetRandPhoneNum'))
drop function GetRandPhoneNum
go
create function GetRandPhoneNum(@operator nvarchar(50)='0',@seed nvarchar(36))
returns nvarchar(11)
as
begin
--@operator:0-随机,1-中国电信号段,2-中国联通号段,3-中国移动号段,4-中国广电号段
--@seed:固定传入newid(),函数不支持newid和rand
declare @phongNum nvarchar(11)--随机手机号码
declare @operatorStart nvarchar(3)--3位运营商号码段
declare @randNum nvarchar(8)--8位随机数
declare @size int--号段数组大小
declare @rand int--号段数组索引
declare @operatorTemp nvarchar(1000)--号段数组
declare @operatorDianxin nvarchar(1000)='133、149、153、173、177、180、181、189、190、191、193、199、'--中国电信号段
declare @operatorLianTong nvarchar(1000)='130、131、132、145、155、156、166、167、171、175、176、185、186、196、'--中国联通号段
declare @operatorYiDong nvarchar(1000)='134、135、136、137、138、139、144、147、148、150、151、152、157、158、159、172、178、182、183、184、187、188、195、197、198、'--中国移动号段
declare @operatorGuangDian nvarchar(1000)='192、'--中国广电号段
declare @operatorAll nvarchar(1000)=@operatorDianxin+@operatorLianTong+@operatorYiDong+@operatorGuangDian--全号段
if(@operator='1')
begin
set @operatorTemp=@operatorDianxin
end
else if(@operator='2')
begin
set @operatorTemp=@operatorLianTong
end
else if(@operator='3')
begin
set @operatorTemp=@operatorYiDong
end
else if(@operator='4')
begin
set @operatorTemp=@operatorGuangDian
end
else
begin
set @operatorTemp=@operatorAll
end
set @randNum=RIGHT(100000000 + CONVERT(bigint, ABS(CHECKSUM(@seed))), 8)
set @size=len(@operatorTemp)/4
set @rand=@randNum%@size
set @operatorStart=SUBSTRING(@operatorTemp,@rand*4+1,3)
set @phongNum=@operatorStart+@randNum
return @phongNum
end
go
4、测试
测试用sql语句:
--测试
select dbo.GetRandPhoneNum(1,newid())--1-中国电信号段
select dbo.GetRandPhoneNum(2,newid())--2-中国联通号段
select dbo.GetRandPhoneNum(3,newid())--3-中国移动号段
select dbo.GetRandPhoneNum(4,newid())--4-中国广电号段
select dbo.GetRandPhoneNum(0,newid())--0-随机
select dbo.GetRandPhoneNum(default,newid())--0-随机
测试结果:
1-中国电信号段
2-中国联通号段
3-中国移动号段
4-中国广电号段
0-随机
5、参考链接
1、SQL Server生成随机手机号
2、Sqlserver产生不重复随机数
3、SQLServer随机数的获取
4、sqlserver数据库中随机生成N位的随机数
5、在SQL SErver中实现数组功能
6、SQLServer函数支持默认参数吗?
7、百度百科:手机号码