SQL小技巧一拼音首字母的模糊查询

创建函数,把中文字段翻译成拼音缩写,例如“你好”翻译成“NH”

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION   [dbo].[fun_GetPy](@str   NVARCHAR(4000)) 
RETURNS   NVARCHAR(4000) 
AS 
BEGIN 
DECLARE   @strlen   INT,@re   NVARCHAR(4000) 
DECLARE   @t   TABLE(chr   NCHAR(1)   COLLATE   Chinese_PRC_CI_AS,letter   NCHAR(1)) 
INSERT   INTO   @t(chr,letter) 
    SELECT   '', 'A '   UNION   ALL   SELECT   '', 'B '   UNION   ALL 
    SELECT   '', 'C '   UNION   ALL   SELECT   '', 'D '   UNION   ALL 
    SELECT   '', 'E '   UNION   ALL   SELECT   '', 'F '   UNION   ALL 
    SELECT   '', 'G '   UNION   ALL   SELECT   '', 'H '   UNION   ALL 
    SELECT   '', 'J '   UNION   ALL   SELECT   '', 'K '   UNION   ALL 
    SELECT   '', 'L '   UNION   ALL   SELECT   '', 'M '   UNION   ALL 
    SELECT   '', 'N '   UNION   ALL   SELECT   '', 'O '   UNION   ALL 
    SELECT   '', 'P '   UNION   ALL   SELECT   '', 'Q '   UNION   ALL 
    SELECT   '', 'R '   UNION   ALL   SELECT   '', 'S '   UNION   ALL 
    SELECT   '', 'T '   UNION   ALL   SELECT   '', 'W '   UNION   ALL 
    SELECT   '', 'X '   UNION   ALL   SELECT   '', 'Y '   UNION   ALL 
    SELECT   '', 'Z ' 
    SELECT   @strlen=LEN(@str),@re= ' ' 
    WHILE   @strlen> 0 
    BEGIN 
        SELECT   TOP   1   @re=letter+@re,@strlen=@strlen-1 
            FROM   @t   a   WHERE   chr <=SUBSTRING(@str,@strlen,1) 
            ORDER   BY   chr   DESC 
        IF   @@rowcount=0 
            SELECT   @re=SUBSTRING(@str,@strlen,1)+@re,@strlen=@strlen-1 
    END 
    RETURN(@re) 
END
GO

执行函数如下图:

 

posted @ 2020-11-13 17:39  海角之上  阅读(901)  评论(0编辑  收藏  举报