对返回100多行的存储过程使用临时表或表变量

时间:2011-02-18 17:47:16

标签: sql-server-2008 stored-procedures temp-tables coldfusion-8

好的,基本上我正在创建一个存储过程,它将为我们的coldfusion power search返回数据。

我创建了一个视图,用于保存多个表中的数据,当然返回了相同的列名。

然后在我的存储过程中,我创建了一个像这样的简单临时表....

    CREATE TABLE #TempSearchResults
(
    search_id int identity,
    id integer,
    type varchar(20),
    title varchar(50),
    url varchar(250),
    rank integer
)

然后我添加了一个索引,在我可能有限的经验中作为一种提高性能的方法。

CREATE UNIQUE INDEX idx on #TempSearchResults (search_id)

然后我选择了大量查询

insert into #TempSearchResults
select id, type, title, url, rank + 1200 as rank
from my view
where company_id = @company_id
and title like @keyword
union all
select id, type, title, url, rank + 1100 as rank
from my view
where company_id = @company_id
and title like @keyword
and description like @keyword

并且它继续像在表中找到关键字的位置具有不同的等级数学值。

最后它确实......

select id, type, title, url, rank
from #TempSearchResults
group by id, type, title, url, rank
order by rank desc, title asc;

现在,当我在coldfusion中测试该存储过程时,似乎需要很长时间。

所以我在想,要么我使用临时表错误还是不完整以获得最佳性能。

或许我应该切换到表变量......

但我只是在阅读...... Temp Tables VS Table Variables

有趣的是,这个存储过程似乎比我直接通过coldfusion运行查询慢,我不喜欢。

我希望获得最佳表现....

谢谢...

以下是我正在使用的视图的基本逻辑或代码。

select some field as id, some field as title, some field as description, 'url link' as url, 1 as rank
from table a
union
select some field as id, some field as title, some field as description, 'url link' as url, 1 as rank
from table b
union
select some field as id, some field as title, some field as description, 'url link' as url, 1 as rank
from table c

等等。我无法透露确切的细节,因为那将是一个安全漏洞。我希望这更清楚。

2 个答案:

答案 0 :(得分:2)

我认为根本不需要使用临时表或表变量。你可以写

select id, type, title, url, rank
from (
    select id, type, title, url, rank + 1200 as rank 
    from my view 
    where company_id = @company_id and title like @keyword 

    union all 

    select id, type, title, url, rank + 1100 as rank 
    from my view 
    where company_id = @company_id and title like @keyword and description like @keyword
) as t
group by id, type, title, url, rank
order by rank desc, title asc;

修改

通过UNION替换UNION ALL,可以简化为

select id, type, title, url, rank + 1200 as rank 
from my view 
where company_id = @company_id and title like @keyword 

union 

select id, type, title, url, rank + 1100 as rank 
from my view 
where company_id = @company_id and title like @keyword and description like @keyword

order by rank desc, title asc;

答案 1 :(得分:0)

在您选择数据的表格上使用with (Nolock)提示;如果您的应用程序允许脏读,它可能会提高性能。