我正在尝试执行以下存储过程,它需要永远执行它以获得更多记录。有什么办法可以用更好/优化的方式写这个
DECLARE productcursor CURSOR FOR
SELECT ProductId,
product_startdate
FROM Products
WHERE ProductStatus IN ('F', 'R', 'M')
GROUP BY productId
OPEN productcursor
FETCH NEXT FROM productcursor INTO @var_PId,@var_PStartDate
WHILE (@@FETCH_STATUS = 0)
BEGIN
SELECT @var_count = count(*) FROM Products
WHERE ProductID IN ((
SELECT ProductID FROM Products
WHERE ProductStatus IN ('OR', 'OP')
AND Comments LIKE '%CANCELLED%'
except ( SELECT ProductID FROM Products WHERE ProductStatus = 'DE'
UNION
SELECT ProductID FROM Products WHERE ProductStatus = 'OR' AND Comments NOT LIKE '%CANCELLED%'
))
except ( SELECT ProductID FROM Products
WHERE ProductStatus IN ('RE', 'C', 'S', 'D')
))
and productid = @var_PId
if @var_count = 0
INSERT INTO ProductDel
(ProductID, ProductDate, ProductDelStatus)
VALUES (@var_PID, @var_PStartDate, 'UNKNOWN')
else
INSERT INTO ProductDel
(ProductID, ProductDate, ProductDelStatus)
VALUES (@var_PID, @var_PStartDate, 'INService')
FETCH NEXT FROM productcursor INTO @var_PId,@var_PStartDate
END
Close productcursor
Deallocate productcursor
正如建议的那样,我可以在没有光标的情况下完成这项工作,但仍然需要永远执行这个......百万记录超过 2 小时 这是此 http://sqlfiddle.com/#!6/b14eb的 sql fiddle 链接/56