中文首字母搜素的实现 sql函数

时间:2021-06-30 08:09:07
-- ============================================= 
-- Author: Jinlong 
-- Create date: 2012-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'' 
) T 
WHERE word>=@word COLLATE Chinese_PRC_CS_AS_KS_WS 
ORDER BY PY ASC) ELSE @word END) 
SET @str=right(@str,len(@str)-1) 
END 
RETURN @PY 
END 

 后台调用

 wheresql = "User_Chinesename in (SELECT User_Chinesename FROM LXSGL_User WHERE dbo.fun_getPY(User_Chinesename) LIKE N'%" + Txt_CXZ.Text.Trim() + "%')";
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Chenxf>
-- Create date: <2009-12-15>
-- Description: <汉语拼音首字简码>
-- =============================================
CREATE FUNCTION [Basic].[funGetPinYin] 
(
@Str nvarchar(500)=''
)
RETURNS varchar(500)
AS
BEGIN

declare @strlen int,@return varchar(500),@ii int 
declare @n int,@c char(1),@chn nchar(1) 

select @strlen=len(@str),@return='',@ii=0 
set @ii=0 
while @ii<@strlen 
begin 
select @ii=@ii+1,@n=63,@chn=substring(@str,@ii,1) 
select @n = @n +1 
,@c = case chn when @chn then char(@n) else @c end 
from( 
select top 27 * from ( 
select chn = '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select '' 
union all select @chn) as a 
order by chn COLLATE Chinese_PRC_CI_AS 
) as b 
set @return=@return+@c 
end 
RETURN(@return) 

END