本文讲一下在.net下如何根据汉字的拼音首字母来搜索数据库,在一些行业中适应比较高,比如:医院、商店行业。
下面介绍几种方法:
方法一:先查询出所有记录,然后在逻辑层转化为拼音首字母后查询,显然傻瓜才会这么做。
方法二:在需要搜索的表中添加一个字段用于存放被检索字段内容对应的拼音,在搜索的时候同时去查询这两个字段,这种方法可行,但会增加数据库存放的大小。
方法三:在数据库中建立一个函数,在执行查询语句时通过此函数来转化搜索,函数如下:
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- -- =============================================
- -- Author: xoyozo
- -- Create date: 2010-4-17
- -- Description: 提供中文首字母
- -- =============================================
- CREATE FUNCTION fun_getPY
- (
- @str NVARCHAR(4000)
- )
- RETURNS NVARCHAR(4000)
- AS
- BEGIN
- DECLARE @word NCHAR(1),@PY NVARCHAR(4000)
- SET @PY=''
- WHILE len(@str)>0
- BEGIN
- SET @word=left(@str,1)
- SET @PY=@PY (CASE WHEN unicode(@word) BETWEEN 19968 AND 19968 20901
- THEN (SELECT TOP 1 PY FROM (
- SELECT 'A' AS PY,N'驁' AS word
- 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'攈'
- 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'咗'