0

我有一个条件,我需要从一个主表中提取 id,然后基于该值从两个不同的表中提取值,然后使用这些值更新/插入第三个表。

我正在使用游标遍历主表中的记录,但是我觉得这会导致性能问题。我想知道这是否可以使用 CTE 来完成。我尝试使用 CTE,但它是非递归的,我完全迷失在哪里出错了。

这是我的存储过程的方式 -

//
BEGIN

declare @variables char(10);
DECLARE @cursor CURSOR; --DECLARE CURSOR
SET @cursor = CURSOR FOR -- SET CURSOR
    -- pull in value for curso
OPEN @cursor
FETCH NEXT
FROM @cursor INTO @variables --FILL IN CURSOR TO LOOP THROUGH

WHILE @@FETCH_STATUS = 0 
    BEGIN

        BEGIN
            --PUll values from table 1
        END
        BEGIN
            --Pull values from table 1
            -- Do some maths on the values pulled
        END
        BEGIN
            --function/sql to  update or insert
        END 


    FETCH NEXT
        FROM @cursor INTO @variables;
    END
    CLOSE @cursor;
    DEALLOCATE @cursor;

END
//

使用 CTE,我的代码是 -

//

;WITH CTE AS 
    (
    --pull values from master table
)


BEGIN
     BEGIN
         -- pull values from table 1
     END
 BEGIN
         -- Pull values from table 2, do the calculations
 END
 BEGIN
          -- insert or update as needed. 
 END
//
4

0 回答 0