检查列是否包含任何关键字的最佳方法是什么

时间:2016-09-30 09:29:18

标签: sql-server sql-server-2012

我有关键字表

关键词:

KeyID | Keyword
 1      Small
 2      Medium
 3      Large
 4      XXLarge

然后我有另一张桌子" Logs"有超过10万条记录。

日志:

LogId | Description
1        blah blah.. Medium blah
2        dsdms    Large whatever

我想在Logs表中添加另一列作为KeyId,然后浏览每个Description以查找它是否包含关键字,然后将KeyId设置为从该行条目的关键字表中更正KeyID。

实现这一目标的最快方法是什么?

2 个答案:

答案 0 :(得分:0)

我尝试了以下方式。请检查:

create table one(
keyid int,
keyword varchar(10)
)


insert into one values (1,'Small')
insert into one values (2,'Medium')
insert into one values (3,'Large')
insert into one values (4,'XXLarge')

create table two(
logid int,
description varchar(100))

insert into two values ('1','blah blah.. Medium blah')
insert into two values ('2','dsdms    Large whatever')


alter table two add  keyid int

根据您的要求,这是查询

declare @query varchar(800),@keyid int,@keyword  varchar(100),@description varchar(max),@LOGID INT

declare d cursor for 
select keyid,keyword from one
open d
fetch next from d into @keyid,@keyword
while @@FETCH_STATUS=0
begin

declare c cursor for
select DESCRIPTION,LOGID from two
open c
fetch next from c into @description, @logid
while @@FETCH_STATUS=0
BEGIN

set @query='if exists(select * from two where upper(description) like ''%' +upper(@keyword)+'%'' and logid='+cast(@LOGID as varchar(max))+' )
begin
update two set keyid=(select keyid from one where upper(keyword)=''' +upper(@keyword)+''') where logid='+cast(@LOGID as varchar(max))+'
end'
print @query
exec (@query)

fetch next from c into @description, @logid
end
close c
deallocate c

fetch next from d into @keyid,@keyword
end
close d
deallocate d

select * from two

答案 1 :(得分:0)

使用为我们提供的示例数据@RanjanaGhimire(非常感谢您),以下查询可能就足够了:

package main

import (
    "bytes"
    "io"
    "io/ioutil"
    "log"
    "strings"
)

func main() {
    r := strings.NewReader("some io.Reader stream to be read\n")
    var buf bytes.Buffer
    tee := io.TeeReader(r, &buf)

    log.Println(ioutil.ReadAll(tee))
    log.Println(ioutil.ReadAll(&buf)) 
}