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

基于Microsoft SQL Server 的标量值函数fun_GetPy,借鉴其他优秀的博主文章,此处贴出源码,以及使用方法

1、打开新建查询,贴如下代码,F5

/****** Object:  UserDefinedFunction [dbo].[fun_GetPy]    Script Date: 11/01/2019 11:07:35 ******/
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

2、执行后,刷新数据库,在可编程性下标量值函数中会看到此函数,安装了SQL Prompt的小伙伴们,需要Refresh Suggestions。

注:提取码为 s4ka 。

SQL Prompt 提供的版本完美兼容数据库2008,2014,如不兼容自行百度下载

3、使用方法

SELECT *FROM [TableName] WHERE 1=1 AND (dbo.fun_GetPy([字段]) LIKE '%"+[参数]+"%' OR [字段] LIKE '%"+参数+"%')"

 

本文个人收藏使用,如有侵权,请联系作者删除!

你可能感兴趣的:(SQL小技巧(一)拼音首字母的模糊查询)