SQL从中文中获取拼音首字母

时间:2022-02-03 08:05:37

今天做开发,客户要求,输入拼音首字母,就能获取表中所有客户名称。

 

步骤:在数据库上造个函数,然后调用这个函数即可

 

1 select dbo.fnpbGetPYFirstLetter(FName) as chinaname,FName from t_Organization
2
3 --fnpbGetPYFirstLetter() 函数名
4 --FName 参数
SQL从中文中获取拼音首字母SQL从中文中获取拼音首字母
 1 --全部扔进去执行,不用修改
2 Create FUNCTION dbo.fnpbGetPYFirstLetter
3 (
4 @str NVARCHAR(4000)
5 )
6 /*
7 select dbo. fnpbGetPYFirstLetter ('中國香港')
8 */
9 RETURNS NVARCHAR(4000)
10 --WITH ENCRYPTION
11 AS
12 BEGIN
13 DECLARE @WORD NCHAR(1),@PY NVARCHAR(4000)
14
15 SET @PY=''
16
17 WHILE LEN(@STR)>0
18 BEGIN
19 SET @WORD=LEFT(@STR,1)
20
21 --如果非漢字字符﹐返回原字符
22 SET @PY=@PY+(CASE WHEN UNICODE(@WORD) BETWEEN 19968 AND 19968+20901
23 THEN (
24 SELECT TOP 1 PY
25 FROM
26 (
27 SELECT 'A' AS PY,N'' AS WORD
28 UNION ALL SELECT 'B',N'簿'
29 UNION ALL SELECT 'C',N''
30 UNION ALL SELECT 'D',N''
31 UNION ALL SELECT 'E',N''
32 UNION ALL SELECT 'F',N''
33 UNION ALL SELECT 'G',N''
34 UNION ALL SELECT 'H',N''
35 UNION ALL SELECT 'J',N''
36 UNION ALL SELECT 'K',N''
37 UNION ALL SELECT 'L',N''
38 UNION ALL SELECT 'M',N''
39 UNION ALL SELECT 'N',N''
40 UNION ALL SELECT 'O',N''
41 UNION ALL SELECT 'P',N''
42 UNION ALL SELECT 'Q',N''
43 UNION ALL SELECT 'R',N''
44 UNION ALL SELECT 'S',N''
45 UNION ALL SELECT 'T',N''
46 UNION ALL SELECT 'W',N''
47 UNION ALL SELECT 'X',N''
48 UNION ALL SELECT 'Y',N''
49 UNION ALL SELECT 'Z',N''
50 ) T
51 WHERE WORD>=@WORD COLLATE CHINESE_PRC_CS_AS_KS_WS
52 ORDER BY PY ASC
53 )
54 ELSE @WORD
55 END)
56 SET @STR=RIGHT(@STR,LEN(@STR)-1)
57 END
58
59 RETURN @PY
60
61 END
62
63 Go
View Code