SQL函数实现综合模糊查询
2016-04-05 21:17
369 查看
--创建函数
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
------------------------------
我的程序生活
程序员的生活
程序员一生的活路
*/
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
------------------------------
我的程序生活
程序员的生活
程序员一生的活路
*/
相关文章推荐
- MYSQL添加新用户 MYSQL为用户创建数据库 MYSQL为新用户分配权限
- SQL语句 SELECT LIKE like用法详解
- 浅谈SQL注入基础
- 第一章:MySql数据库入门
- redis(三)--Java代码-telnet可以连接成功但是出现Connect timeout问题-解决方案
- TimesTen数据库的备份和恢复
- mysql创建自定义函数
- SQL Sever——无法连接到(local)。“未配置远程连接”和“请求失败或服务未及时响应”
- 如何向数据库插入带有单引号(')的字符串?
- 数据库连接jndi
- Mysql 不同版本 说明
- SQLite数据库的运用:
- SQL语言基础入门总结
- MySQL添加分区添加索引
- 从其他主机登陆mysql提示不允许连接的解决办法
- Redis未授权访问事故记录
- mysql
- Ubuntu查看MySQL的数据库data存放路径
- Navicat的1045mysql Access denied for user \'root\'@\'localhost\'”解决办法总结
- 云应用开发之新浪SAE读写云端数据库MySQL