DECLARE 
  @v_id_user INT,
  @v_no_polis VARCHAR(11)

DECLARE list_cursor CURSOR FOR  
SELECT
  id_user,
  no_polis
FROM
  dbo.custport_user_login
WHERE
  activation_queue = 1

OPEN list_cursor  
FETCH NEXT FROM list_cursor INTO @v_id_user, @v_no_polis

WHILE @@FETCH_STATUS = 0  
BEGIN

  IF EXISTS(
            SELECT
  	          *
            FROM
  	          dbo.Polis_Asuransi AS pa INNER JOIN
  	          dbo.Note_Terbit_Master AS ntm ON pa.No_Proposal = ntm.No_Proposal INNER JOIN
  	          dbo.Note_Lunas_Master AS nlm ON ntm.No_Ref = nlm.No_Ref
            WHERE
              pa.No_Polis = @v_no_polis
              AND pa.Tgl_Mulai <= dbo.func_fixed_date(GETDATE())
              AND pa.Tgl_Selesai >= dbo.func_fixed_date(GETDATE())
              AND pa.Status = 'I'
              AND ntm.Jenis IN (1,2)
           )
    BEGIN
      INSERT INTO custport_user_activation_email
                 ([id_user]
                 ,[email_to]
                 ,[email_link]
                 ,[queue]
                 ,[onprocess]
                 ,[sent]
                 ,[sent_date]
                 ,[create_date])
      SELECT
        id_user,
        username,
        NULL,
        1,
        0,
        0,
        NULL,
        GETDATE()
      FROM
        dbo.custport_user_login
      WHERE
        activation_queue = 1
        AND status = 'I'
        AND id_user = @v_id_user
      
      UPDATE
        dbo.custport_user_login
      SET
        activation_queue = 0
      WHERE
        id_user = @v_id_user

    END

  FETCH NEXT FROM list_cursor INTO @v_id_user, @v_no_polis
END  

CLOSE list_cursor  
DEALLOCATE list_cursor 

