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+','