CREATE PROCEDURE Pro_GetKeyWordsId
(
@tblName varchar(200),
@_keyword nvarchar(100),--拆分的字符
@retid nvarchar(10),--主键
@splitchar char(1)--拆分的分割字符
)
AS
BEGIN
declare @commaPos int; --保存分割字符的位置
declare @subString varchar(2000); --保存每个临时子串
declare @id varchar(max);---保存查询到的数据ID集合。
declare @strSQL nvarchar(2000); -- 主语句
set NOCOUNT ON;
set @subString=''
set @id=''
set @strSQL=''
set @commaPos = charindex(@SplitChar, @_keyword, 0); --CharIndex
if @commaPos = 0
begin
return 0;
end;
begin tran; --因为有可能是批量操作,所以采用事务
while @commaPos > 0
begin
set @subString = substring(@_keyword, 1, @commaPos - 1); --分割出一个子字符串
--print @[email protected][email protected];
set @strSQL = 'select @[email protected]+convert(nvarchar,[email protected]+')+'','' from [email protected]+' where charindex([email protected]+''',keyword)>0';
--select @[email protected]+convert(nvarchar,@retid)+',' from @tblname where charindex(@subString ,keyword)>0;
--print @strSQL;
exec sp_executesql @strSQL , [email protected] varchar(max) output ',@id output;
--print @id;
set @_keyword = substring(@_keyword, @commaPos + 1, len(@_keyword)); --
set @commaPos = charindex(@SplitChar, @_keyword, 0);
end;
if @@error = 0
commit tran; --因为启用了事务,所以这里要做处理
else
rollback tran;
set @id=substring(@id,1,len(@id)-1);
select [email protected];
END;
--exec Pro_GetKeyWordsId 'tb_news','车用竹炭包,车内空气质量,车用,竹炭包,质量,空气,车内,热销,车,引人关注','id',','
这个是我的存储过程,它的作用是,查询出所有关键词存在的ID,并拼凑成一个字符串。我数据量有几百万条,假如执行的时候,关键词比较多的话,运行速度超级慢,怎么优化一下呢?
在线等~~~!
------解决方案--------------------
现在需要多久呢
------解决方案--------------------
用charindex查询,加索引基本无效
------解决方案--------------------
有些查询慢是没有办法的
------解决方案--------------------
建个表Table记录你处理过的数据的 ID,
存储过程中加条件 where ID>@id
每次执行 update table set [email protected]
下次执行数据就没有这么多了
------解决方案--------------------
- SQL code
select '车' as 类型,id from table where 字段 like '%车%'unionselect '汽车' as 类型,id from table where 字段 like '%汽车%'unionselect '大众汽车' as 类型,id from table where 字段 like '%大众汽车%'