SQL中根据汉字的拼音首字母模糊查询

 1 ---测试数据---
2 ifobject_id('[pactinfo]') isnotnulldroptable[pactinfo]
3 go
4 createtable[pactinfo]([ID]int,[pactname]varchar(4))
5 insert[pactinfo]
6 select1,'正常'unionall
7 select2,'中国'unionall
8 select3,'做饭'unionall
9 select4,'加发'
10
11 ---引用前辈们的一个函数---
12 createfunction f_GetPy(@str nvarchar(4000))
13 returns nvarchar(4000)
14 as
15 begin
16 declare @strlen int,@re nvarchar(4000)
17 declare @t table(chr nchar(1) collate Chinese_PRC_CI_AS,letter nchar(1))
18 insert into @t(chr,letter)
19 select '', 'A ' union all select '', 'B ' union all
20 select '', 'C ' union all select '', 'D ' union all
21 select '', 'E ' union all select '', 'F ' union all
22 select '', 'G ' union all select '', 'H ' union all
23 select '', 'J ' union all select '', 'K ' union all
24 select '', 'L ' union all select '', 'M ' union all
25 select '', 'N ' union all select '', 'O ' union all
26 select '', 'P ' union all select '', 'Q ' union all
27 select '', 'R ' union all select '', 'S ' union all
28 select '', 'T ' union all select '', 'W ' union all
29 select '', 'X ' union all select '', 'Y ' union all
30 select '', 'Z '
31 select @strlen=len(@str),@re=''
32 while @strlen>0
33 begin
34 select top 1 @re=letter+@re,@strlen=@strlen-1
35 from @t a where chr <=substring(@str,@strlen,1)
36 order by chr desc
37 if @@rowcount=0
38 select @re=substring(@str,@strlen,1)+@re,@strlen=@strlen-1
39 end
40 return(@re)
41 end
42
43
44 ---查询---
45 select
46 *
47 from
48 [pactinfo]
49 where
50 left(dbo.f_GetPy(pactname),1)='Z'
51
52 ---结果---
53 ID pactname
54 ----------- --------
55 1 正常
56 2 中国
57 3 做饭

 

转载于:https://www.cnblogs.com/lilwzca/archive/2011/11/17/2253020.html

你可能感兴趣的:(SQL中根据汉字的拼音首字母模糊查询)