37.生成查询的模糊匹配字符串

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_Sql]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_Sql]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[序数表]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [序数表]
GO

--为了效率,所以要一个辅助表配合
select top 1000 id=identity(int,1,1) into 序数表 
from syscolumns a,syscolumns b
alter table 序数表 add constraint pk_id_序数表 primary key(id)
go

/*--根据指定字符串生成查询的模糊匹配字符串

	条件连接的关键字为 and,or
	可以任意指定括号
	生成的条件表达式为 like 模糊匹配

*/

/*--调用示例

	--调用示例
	select A=dbo.f_Sql('(Web or HTML or Internet) and (Programmer or Developer)','content')
	select B=dbo.f_Sql('Web or HTML or Internet','content')
	select C=dbo.f_Sql('(Web and HTML)','content')
	select D=dbo.f_Sql('Web','content')
--*/
--示例函数
create function f_Sql(
@str Nvarchar(1000),	--要检索的字符串
@fdname sysname	--在那个字段中检索
)returns Nvarchar(4000)
as
begin
	declare @r Nvarchar(4000)
	set @r=''
	select @r=@r+case
		when substring(@str,id,charindex(' ',@str+' ',id)-id) in('or','and')
			then ' '+substring(@str,id,charindex(' ',@str+' ',id)-id)+' '
		when substring(@str,id,1)='('
			then '(['+@fdname+'] like ''%'
				+substring(@str,id+1,charindex(' ',@str+' ',id)-id-1)
				+'%'''
		when substring(@str,charindex(' ',@str+' ',id)-1,1)=')'
			then '['+@fdname+'] like ''%'
				+substring(@str,id,charindex(' ',@str+' ',id)-id-1)
				+'%'')'
		else '['+@fdname+'] like ''%'
			+substring(@str,id,charindex(' ',@str+' ',id)-id)
			+'%'''
		end
	from 序数表
	where id<=len(@str)
		and charindex(' ',' '+@str,id)-id=0
	return(@r)
end
go


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值