SQL-慢速游标简单存储过程
我有一个相对简单的存储过程,但是事务表中的数据量导致它需要花费很长时间才能运行。任何关于优化查询或将其转换为不使用游标的方法的建议都将不胜感激SQL-慢速游标简单存储过程,sql,sql-server,stored-procedures,cursor,Sql,Sql Server,Stored Procedures,Cursor,我有一个相对简单的存储过程,但是事务表中的数据量导致它需要花费很长时间才能运行。任何关于优化查询或将其转换为不使用游标的方法的建议都将不胜感激 BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @ItemID uniqueidentifier SET @CurrentCount = 0;
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @ItemID uniqueidentifier
SET @CurrentCount = 0;
DECLARE @TempTransTable TABLE
(
ID uniqueidentifier
)
-- Insert statements for procedure here
DECLARE curs_GetAllItems CURSOR LOCAL STATIC FORWARD_ONLY READ_ONLY FOR
select
ID
from
item
where
locationid in
(
-- gets corona locations
select
Locations.ID
from Locations
left outer join unit
on unit.locationid = locations.id
where unit.unittype = '4'
)
and stat not in (1,10,11,13) -- only items not in stock
OPEN curs_GetAllItems
FETCH NEXT FROM curs_GetAllItems INTO @ItemID
WHILE (@@FETCH_STATUS =0)
BEGIN
-- Clear table to ensure accurate data
DELETE FROM @TempTransTable
-- Insert transaction records to delete
-- Every transaction except the first two and the last
INSERT INTO @TempTransTable
select
ID
from
transactions
where
transactions.id not in
(select ID from (select top 2 * from transactions where itemid = @ItemID order by transdate asc) as t1
union
select ID from (select top 1 * from transactions where itemid = @ItemID order by transdate desc) as t2)
and itemid = @ItemID
-- Delete trans records
DELETE FROM
dbo.transactions
WHERE
transactions.ID in (select ID from @TempTransTable);
-- Get next item.id
FETCH NEXT FROM curs_GetAllItems INTO @ItemID
END
CLOSE curs_GetAllItems
DEALLOCATE curs_GetAllItems
END
我认为你应该重新审视你的方法。 应该可以在根本不使用游标和循环的情况下进行管理。 可能您需要使用中间临时表(考虑向其中添加索引)
另一点:如果这些查询很困难,并且它们在数据库中工作,同时发生更改,那么您很容易遇到问题—锁、超时和数据不一致。您究竟为什么要使用光标来解决这些问题?这是一种基于集合的时尚@HLGEM只是缺少SQL方面的经验。我正在努力解决这个问题,我会看看你发布的链接。谢谢
;with tmp as (
select *,
rn_asc = ROW_NUMBER() over (partition by t.itemid order by transdate asc),
rn_desc = ROW_NUMBER() over (partition by t.itemid order by transdate desc)
from transactions t
where exists (
select *
from item i
join Locations l on i.locationid = l.ID
join unit u on u.locationid = l.id and u.unittype = '4'
where i.id = t.itemid)
and stat not in (1,10,11,13) -- only items not in stock
)
delete tmp
where rn_asc > 2 and rn_desc > 1;