【SQLServer】函数生成随机手机号

该博客介绍了如何在SQLServer中创建一个函数GetRandPhoneNum,用于生成11位的随机手机号码,支持指定运营商号段或随机选择。函数接受运营商参数和随机种子,通过运算生成不重复的手机号码,可用于测试场景。
摘要由CSDN通过智能技术生成

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-中国电信号段
1-中国电信号段
2-中国联通号段
2-中国联通号段
3-中国移动号段
3-中国移动号段
4-中国广电号段
4-中国广电号段
0-随机
0-随机

5、参考链接

1、SQL Server生成随机手机号
2、Sqlserver产生不重复随机数
3、SQLServer随机数的获取
4、sqlserver数据库中随机生成N位的随机数
5、在SQL SErver中实现数组功能
6、SQLServer函数支持默认参数吗?
7、百度百科:手机号码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值