Home >Database >Mysql Tutorial >A very efficient function for converting Chinese characters to the first letter of Pinyin

A very efficient function for converting Chinese characters to the first letter of Pinyin

大家讲道理
大家讲道理Original
2016-11-10 11:22:021938browse

Scenario:

You need to search for users by the name keywords entered by the user. The user enters the keyword 'x' to search for users (the data comes from the table [Name field] or memory [List])

Requirements:

The resulting sorting should be:

  • x

  • xia

  • xiao

  • yx

That is:

The results containing the letter x should be displayed

The results matching the first letter should be ranked first (such as starting with x)

Same as condition 2 Under the premise, shorter results should be ranked first (for example, x is ranked before xia)

create function [dbo].[fn_getpy2](@Str varchar(500)='')
returns varchar(500)
as
begin
 declare @strlen int,@return varchar(500),@ii int
 declare @n int,@c char(1),@chn nchar(1)

 select @strlen=len(@str),@return='',@ii=0
 set @ii=0
 while @ii<@strlen
 begin
  select @ii=@ii+1,@n=63,@chn=substring(@str,@ii,1)
  if @chn>&#39;z&#39;
  select @n = @n +1
     ,@c = case chn when @chn then char(@n) else @c end
   from(
    select top 27 * from (
     select chn = &#39;吖&#39;
     union all select &#39;八&#39;
     union all select &#39;嚓&#39;
     union all select &#39;咑&#39;
     union all select &#39;妸&#39;
     union all select &#39;发&#39;
     union all select &#39;旮&#39;
     union all select &#39;铪&#39;
     union all select &#39;丌&#39;  --because have no &#39;i&#39;
     union all select &#39;丌&#39;
     union all select &#39;咔&#39;
     union all select &#39;垃&#39;
     union all select &#39;嘸&#39;
     union all select &#39;拏&#39;
     union all select &#39;噢&#39;
     union all select &#39;妑&#39;
     union all select &#39;七&#39;
     union all select &#39;呥&#39;
     union all select &#39;仨&#39;
     union all select &#39;他&#39;
     union all select &#39;屲&#39;  --no &#39;u&#39;
     union all select &#39;屲&#39;  --no &#39;v&#39;
     union all select &#39;屲&#39;
     union all select &#39;夕&#39;
     union all select &#39;丫&#39;
     union all select &#39;帀&#39;
     union all select @chn) as a
    order by chn COLLATE Chinese_PRC_CI_AS 
   ) as b
  else set @c=@chn
  set @return=@return+@c
 end
 return(@return)
end


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn