替代SQL Server中的for循环

时间:2016-06-23 14:35:08

标签: sql-server

我正在尝试将Oracle中的存储过程迁移到Sql server 2014.它中写有两个“for循环”。我想过使用游标但我会很感激,如果有人有更好的游标替代方法或者它是否适合使用它? 该过程从db_1架构中的表中获取每个已删除的程序,并从第二个DB_2中的表中删除关联的值

CREATE OR REPLACE PROCEDURE PD_DELETE
AS
v_PID   VARCHAR2(40 BYTE);
BEGIN

  -- Finding all the deleted subparts in  DB_1
  FOR i IN
  (SELECT ad.ID            AS ID
  , ad.D_FAM          AS D_FAM
  , SUBSTR( ad.ID, 0, 18 ) AS A_fac_id
  , SUBSTR (ad.ID, 20, 7) AS A_CODE
  , SUBSTR( ad.ID, 20 )    AS A_SubCode
   FROM DB_1.IC_DELETE ad
   WHERE ad.IC_Status_ID <> 'P'
   AND ad.D_FAM = 'A_Program_Subpart'
   )

LOOP

Database DB_2

SELECT A_ID INTO v_PID  FROM DB_2.IC_Program
WHERE A_ID = i.a_fac_id
and A_CODE = i.A_CODE;

DELETE
FROM DB_2.AP_SUBPART t
WHERE t.A_ID = v_PID
AND t.SUBPARTCODE = i.A_SubCode;


--- Reset the status in  DB_1
UPDATE DB_1.IC_DELETE ad
SET ad.IC_Status_ID = 'P',
ad.IC_DATE = SYSDATE
WHERE ad.ID = i.ID
AND ad.D_FAM = i.D_FAM;

-- Commit data for a single record
  COMMIT;

END LOOP;

    ========================================  
    SQL SERVER using cursor
    AS
    BEGIN
    Declare @V_ID varchar(40),
    @id varchar(10), @fam varchar(max), @code varchar(max)

    Declare DB_cursor CURSOR LOCAL FORWARD_ONLY FOR 
    Select id, fam, code from IC
       where ind <> 'P'
    OPEN DB_Cursor
    BEGIN 
    FETCH DB_Cursor into @id, @fam, @code
    select @V_id = id from AP
    ...............
      DELETE 
      FROM 
      ..............

      UPDATE 
      .............
      END 
      Close DB_Cursor
      Deallocate DB_Cursor

1 个答案:

答案 0 :(得分:0)

你的专栏和表名真是太神秘了!!!

这是一个黑暗中的镜头,这是不是100%清楚你想要做什么,但我认为这应该是它。

这将取代所有循环。

update ad
SET ind = 'P'
    , date = GETDATE()
from ad
join IC on IC.id = a.ID
where IC.ind <> 'P'

delete IC
from IC
join AP on AP.afid = IC.afacid
    AND AP.acode = IC.code