您的位置:首页 > 其它

新闻相关文章查询语句

2008-06-14 17:12 197 查看
在一个站点中经常使用相关文章

在新闻表中增加 KeyWord字段

在页面中让用户输入关键字时以","号分割

新闻内容

id    title KeyWord

1     a     大,家,好

2     b     家,庭

3     c     你,好,吗

查询id为1的新闻的相关文章

则可以查询出 id为2,3的新闻

create proc TestFindStr  --create proc
(
@id int --新闻id
)
as

declare @TempTable table(keyword VARCHAR(50)) --create temp table
declare @tempstr varchar(50), --temp char

@I INT ,--"," 号 出现位置
@tempkeywords varchar(50) --news keyword

select @tempkeywords=KeyWord from News where id=@id -- 关键字赋值

if @@rowcount=0  --如果行数为0 则返回

begin

return

end

SET @I=CHARINDEX(',', @tempkeywords)  --第一个,位置

WHILE @I>=1

BEGIN

SET @tempstr=LEFT(@tempkeywords, @I-1)  --左边起 截取 出现位置-1

if rtrim(ltrim(@tempstr))<>'' --去左右空格  不为空

begin

insert into @TempTable(keyword) values(@tempstr) --插入到临时表

end

SET @tempkeywords=SUBSTRING(@tempkeywords, @I+1,LEN(@tempkeywords)-@I) --截取 @I 以后字符串

SET @I=CHARINDEX(',', @tempkeywords) --截取后,位置

if(@I<=0) -- 字符串中如果没有 "," 代表已经是最有一个

begin

if rtrim(ltrim(@tempkeywords))<>'' --去左右空格  不为空 确保最后一个字符不为,号

INSERT INTO @TempTable(keyword) VALUES(@tempkeywords) --插入剩余字符到临时表

end

END

-- 以上语句把  "大,家,好," 关键字 字段 分割 存入 临时表

SELECT   distinct  id, t.keyword

FROM   News f,@TempTable t  --内联 确保每个关键字被like

where f.KeyWord like t.keyword+',%' or f.KeyWord like '%,'+t.keyword or f.KeyWord like '%,'+t.keyword+','
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  insert table c