ifexists(select*fromdbo.sysobjectswhereid=object_--为提高效率。idandxtypein dropfunction[dbo].[f_Sql] GO ifexists(select*fromdbo.sysobjectswhereid=object_idandOBJECTPROPERTY droptable[序数表] GO --为了效率,所以要一个辅助表配合 selecttop1000id=identityinto序数表 fromsyscolumnsa,syscolumnsb altertable序数表addconstraintpk_id_序数表primarykey go /*--根据指定字符串生成查询的模糊匹配字符串 条件连接的关键字为and,or 可以任意指定括号 生成的条件表达式为like模糊匹配 --邹建2004.08--*/ /*--调用示例 --调用示例 selectA=dbo.f_Sql('and(ProgrammerorDeveloper)','content') selectB=dbo.f_Sql('WeborHTMLorInternet','content') selectC=dbo.f_Sql','content') selectD=dbo.f_Sql --*/ --示例函数 createfunctionf_Sql,--要检索的字符串 @fdnamesysname--在那个字段中检索 )returnsNvarchar as begin declare@rNvarchar set@r='' select@r=@r+case whensubstring(@str,id,charindexin then''+substring(@str,id,charindex+'' whensubstring='(' then'(['+@fdname+']like''%' +substring(@str,id+1,charindex +'%''' whensubstring(@str,charindex=')' then'['+@fdname+']like''%' +substring(@str,id,charindex +'%'')' else'['+@fdname+']like''%' +substring(@str,id,charindex +'%''' end from序数表 whereid<=len andcharindex-id=0 return end go
--比较第一与第二个字符串,是否有连续的5个字符相同,如果有,返回1,否则返回0
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[f_compstr]') and xtype in (N'FN', N'IF',
N'TF'))
drop function [dbo].[f_compstr]
GO
if exists (select * from dbo.sysobjects where id =
object_id(N'[序数表]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [序数表]
GO
--为提高效率,最好创建一个固定的序数表
select top 1600 id=identity(int,1,1) into 序数表 from sysobjects
a,sysobjects b
go
create function f_compstr(
@str1 varchar(8000),
@str2 varchar(8000)
) returns bit
as
begin
declare @re bit
/*--如果使用动态序数,效率极低.
declare @tb table(id int identity(1,1),a int)
insert into @tb(a) select top 1600 null from sysobjects a,sysobjects
b
--*/
if len(@str1)>len(@str2) set @re=case when exists(
select 1
from (select name=@str2)a,序数表 b --使用动态序数,改为: ,@tb
b
where b.id<=len(@str2)-4 and @str1 like
'%'+substring(name,b.id,5)+'%'
) then 1 else 0 end
else set @re=case when exists(
select 1
from (select name=@str1)a,序数表 b --使用动态序数,改为: ,@tb
b
where b.id<=len(@str1)-4 and @str2 like
'%'+substring(name,b.id,5)+'%'
) then 1 else 0 end
return(@re)
end
go
--调用示例
select
dbo.f_compstr('浦东:田园小区148号405室','浦:田园小区148幢405室')
go
--使用例子,查询不重复的记录,重复的,只显示第一条:
declare @t table(id int identity(1,1),address varchar(1000))
insert into @t
select '浦东:田园小区148号405室'
union all select '浦:田园小区148幢405室'
union all select '浦:田园小区148幢405室'
union all select '浦:田园小区148幢405室'
union all select 'abcdefghijklmn'
union all select 'abcdefg'
union all select 'abcdefghijklmn'
union all select 'abcdefg'
union all select '123456768898'
union all select '123345'
select * from @t a
where id=(select min(id) from @t where
dbo.f_compstr(a.address,address)=1)
/*--测试结果
id address
1 浦东:田园小区148号405室
5 abcdefghijklmn
9 123456768898
10 123345
--*/
编辑:数据库 本文来源:--为提高效率
关键词: