获取拼音首字母函数

 

SQL code
--获取拼音首字母函数 create function f_GetPy(@str nvarchar(4000)) returns nvarchar(4000) as begin declare @strlen int,@re nvarchar(4000) declare @t table(chr nchar(1) collate Chinese_PRC_CI_AS,letter nchar(1)) insert into @t(chr,letter) select '','A' union all select '','B' union all select '','C' union all select '','D' union all select '','E' union all select '','F' union all select '','G' union all select '','H' union all select '','J' union all select '','K' union all select '','L' union all select '','M' union all select '','N' union all select '','O' union all select '','P' union all select '','Q' union all select '','R' union all select '','S' union all select '','T' union all select '','W' union all select '','X' union all select '','Y' union all select '','Z' select @strlen=len(@str),@re='' while @strlen>0 begin select top 1 @re=letter+@re,@strlen=@strlen-1 from @t a where chr<=substring(@str,@strlen,1) order by chr desc if @@rowcount=0 select @re=substring(@str,@strlen,1)+@re,@strlen=@strlen-1 end return(@re) end go --调用 select * from a order by case Name when '其他' then 1 else 0 end,dbo.f_GetPy(Name) --获取字符串拼音字头 --Pqs 2006-11-20 --@Char 输入的字符串 CREATE function dbo.GetPY (@Char varchar(100)) returns varchar(100) as begin --字符串长度 返回数据 遍历字符串位置 遍历的字符 declare @i_Len int, @c_Return varchar(100), @i_pos int,@c varchar(2),@c_CN varchar(100) --初始化数据 --set @str='龙岂池中物' set @i_Len = len(@Char) set @c_Return = '' set @i_pos = 0 --遍历字符串 while (@i_pos < @i_Len ) begin set @i_pos = @i_pos + 1 set @c_CN = substring(@Char, @i_pos, 1) if (@c_CN > 'z' ) --中文处理,查询匹配 begin set @c = case when @c_CN>='' then 'Z' when @c_CN>='' and @c_CN<'' then 'Y' when @c_CN>='' and @c_CN<'' then 'X' when @c_CN>='' and @c_CN<'' then 'W' when @c_CN>='' and @c_CN<'' then 'T' when @c_CN>='' and @c_CN<'' then 'S' when @c_CN>='' and @c_CN<'' then 'R' when @c_CN>='' and @c_CN<'' then 'Q' when @c_CN>='' and @c_CN<'' then 'P' when @c_CN>='' and @c_CN<'' then 'O' when @c_CN>='' and @c_CN<'' then 'N' when @c_CN>='' and @c_CN<'' then 'M' when @c_CN>='' and @c_CN<'' then 'L' when @c_CN>='' and @c_CN<'' then 'K' when @c_CN>='' and @c_CN<'' then 'J' when @c_CN>='' and @c_CN<'' then 'H' when @c_CN>='' and @c_CN<'' then 'G' when @c_CN>='' and @c_CN<'' then 'F' when @c_CN>='' and @c_CN<'' then 'E' when @c_CN>='' and @c_CN<'' then 'D' when @c_CN>='' and @c_CN<'' then 'C' when @c_CN>='' and @c_CN<'' then 'B' when @c_CN>='' and @c_CN<'' then 'A' Else '' End -- select top 1 @c = Code from Code_PY where name <= @c_CN end else begin --过滤字符(除了字符、数字和'.'外的所有字符) if (@c_CN>='a' or (@c_CN>='0' and @c_CN<='9') or @c_CN='.') set @c=@c_CN else set @c='' end set @c_Return=@c_Return+isnull(@c ,'') end return upper(@c_Return) end
posted @ 2008-12-10 10:39  汤包  阅读(342)  评论(0编辑  收藏  举报