在 SQL 服务器中使用游标(可能带有连接)重写查询
Rewrite query using cursor (perhaps with a join) in SQL Server
我有一个查询(不是我自己写的),我正在努力使其 运行 更快。我好像是这个
看不到答案是否适用于我的情况。是否可以重写此查询?
结构是:
TRUNCATE TABLE TableA
declare @myvar as varchar(255)
declare cur CURSOR LOCAL FAST_FORWARD
for SELECT SUB_TRANS
FROM TableB
open cur
fetch next from cur
into @myvar
while @@FETCH_STATUS = 0
BEGIN
INSERT INTO TableA
SELECT many_thing
from 4_tables_with_join(Note: @myvar is included as a join condition)
fetch next from cur
into @myvar
END
close cur
deallocate cur
作为“一般提示”:您很可能根本不需要游标逻辑。我建议将其重写为直接 insert ... select
查询。
作为 pseudo-code,这看起来像:
insert into tablea (col1, col2, ...)
select many_thing
from tableb tb
inner join ... -- use "tb.subtrans" here in the join conditions instead of "@myvar"
我有一个查询(不是我自己写的),我正在努力使其 运行 更快。我好像是这个
看不到答案是否适用于我的情况。是否可以重写此查询?
结构是:
TRUNCATE TABLE TableA
declare @myvar as varchar(255)
declare cur CURSOR LOCAL FAST_FORWARD
for SELECT SUB_TRANS
FROM TableB
open cur
fetch next from cur
into @myvar
while @@FETCH_STATUS = 0
BEGIN
INSERT INTO TableA
SELECT many_thing
from 4_tables_with_join(Note: @myvar is included as a join condition)
fetch next from cur
into @myvar
END
close cur
deallocate cur
作为“一般提示”:您很可能根本不需要游标逻辑。我建议将其重写为直接 insert ... select
查询。
作为 pseudo-code,这看起来像:
insert into tablea (col1, col2, ...)
select many_thing
from tableb tb
inner join ... -- use "tb.subtrans" here in the join conditions instead of "@myvar"