【转载】MSSQL汉字首字母查询处理自定义函数

 

-- 汉字首字母查询处理用户定义函数
CREATE FUNCTION f_GetPY(@str nvarchar(4000))
RETURNS nvarchar(4000)
AS
BEGIN
    DECLARE @py TABLE(
        ch char(1),
        hz1 nchar(1) COLLATE Chinese_PRC_CS_AS_KS_WS,
        hz2 nchar(1) COLLATE Chinese_PRC_CS_AS_KS_WS)
    INSERT @py SELECT 'A',N'',N''
    UNION  ALL SELECT 'B',N'',N'簿'
    UNION  ALL SELECT 'C',N'',N''
    UNION  ALL SELECT 'D',N'',N''
    UNION  ALL SELECT 'E',N'',N''
    UNION  ALL SELECT 'F',N'',N''
    UNION  ALL SELECT 'G',N'',N''
    UNION  ALL SELECT 'H',N'',N''
    UNION  ALL SELECT 'J',N'',N''
    UNION  ALL SELECT 'K',N'',N''
    UNION  ALL SELECT 'L',N'',N''
    UNION  ALL SELECT 'M',N'',N''
    UNION  ALL SELECT 'N',N'',N''
    UNION  ALL SELECT 'O',N'',N''
    UNION  ALL SELECT 'P',N'',N''
    UNION  ALL SELECT 'Q',N'',N''
    UNION  ALL SELECT 'R',N'',N''
    UNION  ALL SELECT 'S',N'',N''
    UNION  ALL SELECT 'T',N'',N''
    UNION  ALL SELECT 'W',N'',N''
    UNION  ALL SELECT 'X',N'',N''
    UNION  ALL SELECT 'Y',N'',N''
    UNION  ALL SELECT 'Z',N'',N''
    DECLARE @i int
    SET @i=PATINDEX('%[吖-做]%' COLLATE Chinese_PRC_CS_AS_KS_WS,@str)
    WHILE @i>0
        SELECT @str=REPLACE(@str,SUBSTRING(@str,@i,1),ch)
            ,@i=PATINDEX('%[吖-做]%' COLLATE Chinese_PRC_CS_AS_KS_WS,@str)
        FROM @py
        WHERE SUBSTRING(@str,@i,1) BETWEEN hz1 AND hz2
    RETURN(@str)
END

 

posted @ 2021-10-25 01:14  深海澜鲸  阅读(95)  评论(0编辑  收藏  举报