日期:2014-05-18  浏览次数:20472 次

求SQL获取拼音首字母函数
1,汉字返回大写拼音首字母
2,   英文返回大写首字母
3,数字返回第一个数字
4,其他文字及符号返回“*”号

------解决方案--------------------
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)

------解决方案--------------------
其他情况自己处理一下。
------解决方案--------------------
猛人啊
------解决方案--------------------
牛人,學習一下
------解决方案--------------------
--1. 按拼音排序
DECLARE @t TABLE(col varchar(2))
INSERT @t SELECT '中 '
UNION ALL SELECT '国 '
UNION ALL SELECT '人 '

SELECT * FROM @t ORDER BY col COLLATE Chinese_PRC_CS_AS_KS_WS
/*--结果
col
----



--*/
GO


/*==========================================*/


--2. 汉字首字母查询处理用户定义函数
CREATE FUNCTION f_GetPY(@str nvarchar(4000))
RETURNS nvarchar(4000)
AS
BEGIN
DECLARE @py TABLE(
ch char(1),
hz1 nchar(1) COLLATE Chinese_PRC_CS_AS_KS_WS,
hz2 nchar(1) COLLATE Chinese_PRC_CS_AS_KS_WS)
INSERT @py SELECT 'A ',N '吖 ',N '鏊 '
UNION ALL SELECT 'B ',N '八 ',N '簿 '
UNION ALL SELECT 'C ',N '嚓 ',N '错 '
UNION ALL SELECT 'D ',N '哒 ',N '跺 '
UNION ALL SELECT 'E ',N '屙 ',N '贰 '
UNION ALL SELECT 'F ',N '发 ',N '馥 '
UNION ALL SELECT 'G ',N '旮 ',N '过 '
UNION ALL SELECT 'H ',N '铪 ',N '蠖 '
UNION ALL SELECT 'J ',N '丌 ',N '竣 '
UNION ALL SELECT 'K ',N '咔 ',N '廓 '
UNION ALL SELECT 'L ',N '垃 ',N '雒 '
UNION ALL SELECT 'M ',N '妈 ',N '穆 '