Link to home
Start Free TrialLog in
Avatar of trojan_uk
trojan_uk

asked on

CDONTS and WHILE (@@FETCH_STATUS)

Hi,

I am trying to loop through a database and send an email out when certain constraints are met, I have used print to see the results which in this case correctly pulls out 4 records, however it only sends 1 email, and ideas on what I am doing wrong?


DECLARE @number varchar(100)
DECLARE @msg varchar(255)
DECLARE fetch_cursor cursor for

SELECT fault_id
FROM report_table
WHERE status ='O' and close_date is null and datediff("d", open_date, getdate())>1
OPEN fetch_cursor

DECLARE @Address varchar(255), @Message varchar(8000),
@Subject varchar(255), @From varchar(255), @CDO int, @OLEResult int, @Out int

EXECUTE @OLEResult = master.dbo.sp_OACreate 'CDONTS.NewMail', @CDO OUT
FETCH NEXT FROM fetch_cursor into @number
WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF (@@FETCH_STATUS <> -2)
BEGIN
      Set @Address = 'peter@whoba.co.uk'
      Set @Message = 'Fault ID (' + @number + ') is still open.'
      Set @Subject  = 'Fault Log Update'
      Set @From = 'peter@whoba.co.uk'
      
IF @OLEResult <> 0

      PRINT 'CDONTS.NewMail'
        PRINT 'ItemNo = ' + @number
        execute @OLEResult = master.dbo.sp_OAMethod @CDO, 'Send', Null, @From, @Address, @Subject, @Message, 0

        IF @OLEResult <> 0 PRINT 'Send'
          PRINT ' '
      END

FETCH NEXT FROM fetch_Cursor INTO @number
END
EXECUTE @OLEResult = master.dbo.sp_OADestroy @CDO
 
CLOSE fetch_Cursor
DEALLOCATE fetch_Cursor


=========== PRINT RESULTS====================

ItemNo = SB7736
 
ItemNo = SB7748
Send
 
CDONTS.NewMail
ItemNo = SB7735
Send
 
CDONTS.NewMail
ItemNo = SB7764
Send
 
===================================

Thanks for any help








ASKER CERTIFIED SOLUTION
Avatar of SQL_Stu
SQL_Stu
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of trojan_uk
trojan_uk

ASKER

Thanks,

Funny enough I had just tried that before your messge came in:

FETCH NEXT FROM fetch_cursor into @number
WHILE (@@FETCH_STATUS <> -1)
BEGIN      
EXECUTE @OLEResult = master.dbo.sp_OACreate 'CDONTS.NewMail', @CDO OUT
IF (@@FETCH_STATUS <> -2)
BEGIN


And it worked, however had I been a few minutes slower you would have given me the right answer.

Thanks again