我想知道在存储过程中使用Views, Temp Tables and Direct Queries
用法的效果。
每次触发触发器时都会创建一个表。我知道这个触发器非常罕见,在安装时只会触发一次。
现在我必须在许多地方使用触发器创建的表来获取数据,并确认没有人在该表中进行任何更改。即ReadOnly
表。
我必须使用此表数据以及多个表来加入并获取结果以进一步查询
select * from triggertable
使用临时表
select ... into #tx from triggertable join t2 join t3 and so on
select a,b, c from #tx --do something
select d,e,f from #tx ---do somethign
--and so on
--around 6-7 queries in a row in a stored procedure.
使用观看
create view viewname
(
select ... from triggertable join t2 join t3 and so on
)
select a,b, c from viewname --do something
select d,e,f from viewname ---do somethign
--and so on
--around 6-7 queries in a row in a stored procedure.
此视图也可以在其他地方使用。所以我将在数据库而不是sp
创建使用直接查询
select a,b, c from select ... into #tx from triggertable join t2 join t3 join ... --do something
select a,b, c from select ... into #tx from triggertable join t2 join t3 join ... --do something
.
.
--and so on
--around 6-7 queries in a row in a stored procedure.
现在,我可以在所有即将进行的查询中创建一个视图/临时表/直接查询用法。
在这种情况下最好使用什么。
答案 0 :(得分:1)
如果triggertable
仅在安装时创建一次,则只需直接查询该表。如果将SQL查询包装在一个事务中,该事务应该阻止其他用户在查询时更新triggertable
。
在这种情况下使用视图没有任何好处。
您可以将triggertable
复制到临时表中,但在这种情况下我看不到任何实际好处。
答案 1 :(得分:0)
是否始终是来自同一来源的数据?如果是这种情况,视图上的索引可以提高性能。
我可以看到临时表的唯一原因是,如果你有一个WHERE
选择一个小的子集,所有后续的6-7查询都可以使用,但你没有说明一种方式或你问题中的另一个。
这两个选项可以结合使用,但还有更多因素没有提及,例如总数据的大小等。
否则我不会打扰并直接查询表格select triggertable.a, t2.b, t3.c from triggertable join t2 join t3 ...