sql server 2008实现拼音首字母和随机n位数的生成 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

    应用背景:

    1、一些商品需要使用汉字拼音首字母快速查找,以便定位和选择数据;

    2、一些系统的用户名可能含有该用户姓名首字母,以方便记忆,我做系统的时候,我习惯把用户名定义为:用户姓名汉字首字母+用户在表中的主键ID,这样不会出现用户名重复,也方便用户记忆,

sql server 2008实现拼音首字母和随机n位数的生成

。 

    3、初始化用户密码的时候,有时需要自动生成n位随即密码。

    说明:技术没有原创,只有在应用中不断吸取他人经验,不断总结

    一、获取拼音首字母的编码和引用

    1、在sqlserver2008中创建标量函数,函数名CreateFirstLetter。

    创建方法:您的数据库-》可编程性=》函数=》标量值函数;

    右键,创建标量值函数CreateFirstLetter。函数体代码如下:

    Create function [dbo].[CreateFirstLetter]

    (

    @col varchar(2000)

    )

    returns varchar(2000)

    begin

    declare @cyc int,@len int,@sql varchar(1000),@char varbinary(20)

    select @cyc = 1,@len = len(@col),@sql = ''

    while @cyc <= @len

    begin

    select @char = cast(substring(@col, @cyc, 1) as varbinary)

    if @char>=0XB0A1 and @char<=0XB0C4   set @sql=@sql+'A'

    else if @char>=0XB0C5 and @char<=0XB2C0 set @sql=@sql+'B'

    else if @char>=0XB2C1 and @char<=0XB4ED set @sql=@sql+'C'

    else if @char>=0XB4EE and @char<=0XB6E9 set @sql=@sql+'D'

    else if @char>=0XB6EA and @char<=0XB7A1 set @sql=@sql+'E'

    else if @char>=0XB7A2 and @char<=0XB8C0 set @sql=@sql+'F'

    else if @char>=0XB8C1 and @char<=0XB9FD set @sql=@sql+'G'

    else if @char>=0XB9FE and @char<=0XBBF6 set @sql=@sql+'H'

    else if @char>=0XBBF7 and @char<=0XBFA5 set @sql=@sql+'J'

    else if @char>=0XBFA6 and @char<=0XC0AB set @sql=@sql+'K'

    else if @char>=0XC0AC and @char<=0XC2E7 set @sql=@sql+'L'

    else if @char>=0XC2E8 and @char<=0XC4C2 set @sql=@sql+'M'

    else if @char>=0XC4C3 and @char<=0XC5B5 set @sql=@sql+'N'

    else if @char>=0XC5B6 and @char<=0XC5BD set @sql=@sql+'O'

    else if @char>=0XC5BE and @char<=0XC6D9 set @sql=@sql+'P'

    else if @char>=0XC6DA and @char<=0XC8BA set @sql=@sql+'Q'

    else if @char>=0XC8BB and @char<=0XC8F5 set @sql=@sql+'R'

    else if @char>=0XC8F6 and @char<=0XCBF9 set @sql=@sql+'S'

    else if @char>=0XCBFA and @char<=0XCDD9 set @sql=@sql+'T'

    else if @char>=0XCDDA and @char<=0XCEF3 set @sql=@sql+'W'

    else if @char>=0XCEF4 and @char<=0XD1B8 set @sql=@sql+'X'

    else if @char>=0XD1B9 and @char<=0XD4D0 set @sql=@sql+'Y'

    else if @char>=0XD4D1 and @char<=0XD7F9 set @sql=@sql+'Z'

    set @cyc = @cyc + 1

    end

    return @sql

    end 

    2、函数使用

    在你的存储过程或者查询窗体中引用该函数即可,

电脑资料

sql server 2008实现拼音首字母和随机n位数的生成》(https://www.unjs.com)。

    注意:必须在在该函数前加 "dbo.“。

    如,我要获取 Name字段的汉字首字母,代码如下

    select dbo.CreateFirstLetter(Name) as  NameFirstLetter from 你的表名

    二、生成n位随即数字

    以下代码是随即生成6位随即数字的代码。

    ABS(CHECKSUM(NEWID())%900000)+100000

    你需要多少位随即数字,就请修改代码里面的0哈。

    以上代码我没有在sql2000和2005中做测试,应该也是行的呢。

    作者 sansitongzhi

最新文章