--============================================
--创建辅助表
IF(OBJECT_ID('dbo.PinYinFirst','U') IS NOT NULL)
BEGIN
DROP TABLE dbo.PinYinFirst
END
GO
CREATE TABLE dbo.PinYinFirst
(
Word NVARCHAR(200),
PY NVARCHAR(200)
)
GO
--=======================================
--插入数据
INSERT INTO dbo.PinYinFirst(PY,Word)
SELECT 'A' AS py, N'吖' AS chn
UNION ALL SELECT 'B',N'八'
UNION ALL SELECT 'C',N'嚓'
UNION ALL SELECT 'D',N'咑'
UNION ALL SELECT 'E',N'妸'
UNION ALL SELECT 'F',N'发'
UNION ALL SELECT 'G',N'旮'
UNION ALL SELECT 'H',N'铪'
UNION ALL SELECT 'J',N'丌' --because have no 'i'
UNION ALL SELECT 'K',N'咔'
UNION ALL SELECT 'L',N'垃'
UNION ALL SELECT 'M',N'嘸'
UNION ALL SELECT 'N',N'拏'
UNION ALL SELECT 'O',N'噢'
UNION ALL SELECT 'P',N'妑'
UNION ALL SELECT 'Q',N'七'
UNION ALL SELECT 'R',N'呥'
UNION ALL SELECT 'S',N'仨'
UNION ALL SELECT 'T',N'他'
UNION ALL SELECT 'W',N'屲'
UNION ALL SELECT 'X',N'夕'
UNION ALL SELECT 'Y',N'丫'
UNION ALL SELECT 'Z',N'帀'
--=======================================
--创建函数,循环遍历字符串,
--使用辅助表来获取遍历得到的字符的拼音首字符
IF(OBJECT_ID('dbo.ufn_GetPyFirst','FN') IS NOT NULL)
BEGIN
DROP FUNCTION dbo.ufn_GetPyFirst
END
GO
CREATE FUNCTION dbo.ufn_GetPyFirst(@Str NVARCHAR(500)='')
RETURNS NVARCHAR(500)
AS
BEGIN
DECLARE @strlen INT;
SELECT @strlen=LEN(@str);
DECLARE @i INT;
DECLARE @result NVARCHAR(500);
SET @result=N''
SET @i=0;
--空字符串返回空
IF(@strlen<1)
BEGIN
RETURN '';
END
WHILE(@i<@strlen)
BEGIN
SET @i=@i+1
DECLARE @tempChar NCHAR(1);
DECLARE @tempPY NCHAR(1);
SET @tempChar=substring(@str,@i,1);
IF(@tempChar>N'z')
BEGIN
SELECT TOP(1) @tempPY=T.py FROM dbo.PinYinFirst T
WHERE T.word<=@tempChar
ORDER BY T.word
COLLATE Chinese_PRC_CI_AS DESC;
SET @result=@result+@tempPY;
END
END
RETURN @result
END
GO
--==============================
--测试
select dbo.ufn_GetPyFirst(N'好人N')