--创建函数
create function [dbo].[m_fuzzyquery_v1]
(
@str nvarchar(2000)
)
returns nvarchar(2000)
as
begin
declare @count int,@i int;
declare @newchar nvarchar(200),@nn nvarchar(300),@hh nvarchar(200)
set @count=len(@str);set @i=1;set @nn='';
while @i<@count+1
begin
set @newchar=substring(@str,@i,1)+'%'
set @nn=@nn+@newchar;
set @i=@i+1;
end
set @hh='%'+@nn
return @hh
end
--测试数据
declare @table table (connect varchar(30))
insert into @table
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 '程序员一生的活路'
--普通的模糊查询
select * from @table where connect like '%程序生活%'
--运行结果
/*
connect
------------------------------
我的程序生活
*/
--应用函数查询
select * from @table where connect like ( select dbo.[m_fuzzyquery_v1]('程序生活'))
--运行结果
/*
connect
------------------------------
我的程序生活
程序员的生活
程序员一生的活路
*/
特别说明:
如果数据量比较大,尽量避免使用自定义函数,以免严重影响性能。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/maco_wang/archive/2011/03/16/6254963.aspx
【叶子函数分享四】综合模糊查询
最新推荐文章于 2025-09-03 16:32:30 发布
本文介绍了一种在SQL中实现模糊查询的方法,通过自定义函数增强通配符的灵活性,适用于部分匹配需求。需要注意的是,这种方法可能会影响性能,不推荐在大数据量场景下使用。
14

被折叠的 条评论
为什么被折叠?



