日期:2014-05-17  浏览次数:20551 次

sql 反向模糊查询的问题
数据库字段中 保存以下数据

1 abc?def
2 bcef??g
3 a??efg


给出字符串 abcddef  能找出 记录1
给出字符串 aabefg   能找出 记录2


请问这个要怎么做?
------最佳解决方案--------------------
declare @t table(id int,col varchar(10))
insert into @t values(1,'abc?def')
insert into @t values(2,'bcef??g')
insert into @t values(3,'a??efg')

declare @str varchar(10)
set @str='abcddef'
select * from @t
where @str like replace(col,'?','_')
--
/*
id      col
-----------------------
1 abc?def
*/

set @str='aabefg'
select * from @t
where @str like replace(col,'?','_')

--
/*
id      col
--------------------------
3 a??efg
*/
------其他解决方案--------------------
引用:
数据库字段中 保存以下数据

1 abc?def
2 bcef??g
3 a??efg


给出字符串 abcddef  能找出 记录1
给出字符串 aabefg   能找出 记录2


请问这个要怎么做?


你这个问题本身就有问题。
如果你数据库中的数据(比如 bcef??g)不定长,或者 要查找的数据(如 aabefg )不定长,
那你查找匹配的时候,怎么匹配?匹配条件是几个字符相同就符合条件呢?

如果都不定长,那你还是全文搜索吧

 
------其他解决方案--------------------
中间插个%不就行咯,干嘛要用_
------其他解决方案--------------------
select * from 表 where repalce(字段,'?','')=查询值
------其他解决方案--------------------
create table #t
([id][int] identity(1,1) not null,
[col][varchar][10] not null,
constraint (tPK) priamry key clustered
)
insert into #t 
(select 1,abc?def union all
select 2,bcef??g union all
select 3,a??efg 
) from #t
update #t
set col=replace(col,'?','') where col='abc?def'
go
update #t
set col=replace(col,'bcef??g''aabefg') where col='bcef??g'
go
------其他解决方案--------------------
select * from 表 where @str like '%'+replace(col1,'?','_')+'%'
------其他解决方案--------------------
这样写 只有给定字符串和 数据库中字符串 长度一致的时候才行啊
------其他解决方案--------------------
我开始的想法中 ? 表示任何单个字符  ,只要这一段 能匹配 就算满足条件
------其他解决方案--------------------
中间匹配的数目是固定的
%号 我试 了下  ,不成功