读书人

怎么从成语库中分别查询ABAC/ABCB/AAB

发布时间: 2012-02-01 16:58:19 作者: rapoo

如何从成语库中分别查询ABAC/ABCB/AABB/ABCC/AABC模式的词条?
如何从成语库中分别查询ABAC/ABCB/AABB/ABCC/AABC模式的词条?

成语库数据库:
表名: idiom
字段: id  int
    word nvarchar(15)
内容: 1 挨家挨户
    2 不打不相识
    3 大吼大叫
    4 八面玲珑
    ……
    ……

[解决办法]
比如,ABAC
select * from idiom where len(word)= 4 and substirng(word,1,1) = substirng(word,3,1)
[解决办法]
还要判断第2,4个单词吧
[解决办法]
create table idiom(id int,word varchar(20))
insert idiom
select 1, '挨家挨户 '
union all select 2, '不打不相识 '
union all select 3, '大吼大叫 '
union all select 4, '八面玲珑 '
union all select 5, '一道山一道梁 '

select * from idiom
drop table idiom

这种东西按字位置单纯用字串函数还是有问题的.
要写函数依次去匹配,也不是难事.

但是,这种东西适合在数据库端做吗? 前端语言那么强大的字符处理及正则为什么不用.
[解决办法]
--理,好像啥好法,

create table idiom(id int,word varchar(20))
insert idiom
select 1, '挨家挨 '
union all select 2, '不打不相 '
union all select 3, '大喉大叫 '
union all select 4, '八面玲 '
union all select 5, '告 '
union all select 6, '相茂堂堂 '

Go

create function fn_test(@id int)
returns nvarchar(15)
AS
begin
declare @str nvarchar(15),@i int,@re nvarchar(15)
set @i=1
select @str=word from idiom where id=@id
while @i> 0 and @i <=len(@str)
begin
if charindex(substring(@str,@i,1),stuff(@str,1,@i, ' '))> 0

select @re=@str,@i=0
else
select @i=@i+1
end
return @re
END

GO

select * from
(
select id,dbo.fn_test(id) as word
from idiom
) t
where word is not null

/*
id word
----------- ---------------
1 挨家挨
2 不打不相
3 大喉大叫
6 相茂堂堂
*/

Go
drop table idiom
drop function fn_test

读书人网 >SQL Server

热点推荐