473,769 Members | 1,752 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cursor loop is broken

In a stored procedure (SP1) I am looping through a cursor with records
from Table1. Each record in the cursor is inserted into Table2.
Insert trigger on Table2 is inserting the record into Table3 (in
another DB).
In the insert trigger on Table3, a series of checks are done on the
inserted record and in case of an error, an email is sent and the
trigger returns.
This break the cursorloop in SP1 and the rest of the records in the
cursor is not treated.
How do I make sure that all records are treated?
This is the flow:
-- SP1 ---------------------------------
DECLARE csrListe CURSOR FOR SELECT felt1 FROM Table1
OPEN csrListe
-- The first record is treated here....
:
-- Treat the rest
WHILE @@FETCH_STATUS = 0 BEGIN
FETCH NEXT FROM csrListe INTO @feltet
IF @@FETCH_STATUS = 0 BEGIN
blah-blah-blah
INSERT INTO Table2 (Ordrenr, Status, Dato, Resultat) VALUES

(@Ordrenr, @Status, @Dato, @Result)
END
END
CLOSE csrListe
DEALLOCATE csrListe
-- Table2_ITrig ---------------------------------
INSERT INTO db2.dbo.Table3 SELECT * FROM inserted
-- Table3_ITrig ---------------------------------
SET NOCOUNT ON
DECLARE @STATUS int
DECLARE @DATOTID smalldatetime
DECLARE @RESULT int
SELECT @ORDRENR = (SELECT ORDRENR FROM INSERTED)
SELECT @STATUS = (SELECT STATUS FROM INSERTED)
SELECT @DATOTID = (SELECT DATO FROM INSERTED)
SELECT @RESULT = (SELECT RESULT FROM INSERTED)
SET XACT_ABORT ON
IF NOT @STATUS IN (1,2,3,4,5,6,9, 10) BEGIN
SELECT @ERR = 'ERROR - unknown status = ' + CAST(@ORDRENR as char(4))

UPDATE Table3 SET RESULTAT=2 WHERE ORDRENUMMER=@OR DRENR
EXEC @rc = master.dbo.xp_s mtp_sendmail
@FROM = N...@here.dk',
@TO = N...@here.dk',
@priority = N'HIGH',
@subject = N'Status error',
@message = N'Status error',
@type = N'text/plain',
@server = 'smtp.here.dk'
RETURN
END
The mail is send so it must be the final RETURN that is causing the
trouble.

Jan 7 '06 #1
1 2038
Søren Larsen (sb****@surfpos t.dk) writes:
In a stored procedure (SP1) I am looping through a cursor with records
from Table1. Each record in the cursor is inserted into Table2.
Insert trigger on Table2 is inserting the record into Table3 (in
another DB).
In the insert trigger on Table3, a series of checks are done on the
inserted record and in case of an error, an email is sent and the
trigger returns.
This break the cursorloop in SP1 and the rest of the records in the
cursor is not treated.
How do I make sure that all records are treated?
An error in a trigger aborts the batch. Thus, in SQL 2000, there is no
way to handle the situation in T-SQL, you would need to have a client
program that reacts on the error, and restarts the loop, but leaving
out the row that causes problems. In SQL 2005, you could use TRY-CATCH
to handle the situation.

But why are you running a loop in the first place? The normal procedure
to insert rows from one table to another is to say:

INSERT tbl2 (...)
SELECT ...
FROM tbl1

Of course, this would mean that if any of the rows are erroneous, then
all rows inserted would be rolled back by the trigger on Table3. But this
can be handled in different ways. (But exactly how, it's difficult to
say as I don't know the business requirements.)

The reason you should insert all, and not run a cursor, is that performance
for a cursor can be disastrous. If we are talking less than < 100 rows, it's
may be not that big deal. If we are talking 10000 rows, it can mean a
difference in processing time of 30 minutes instead of 30 seconds.
-- Table3_ITrig ---------------------------------
SET NOCOUNT ON
DECLARE @STATUS int
DECLARE @DATOTID smalldatetime
DECLARE @RESULT int
SELECT @ORDRENR = (SELECT ORDRENR FROM INSERTED)
SELECT @STATUS = (SELECT STATUS FROM INSERTED)
SELECT @DATOTID = (SELECT DATO FROM INSERTED)
SELECT @RESULT = (SELECT RESULT FROM INSERTED)


This trigger is poorly implemented. A trigger fires once per statement,
and must be able to handle multi-row operations.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Jan 7 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
5147
by: robert | last post by:
Mr. Kyte's article doesn't use cursors, while Mr. Feuerstein's book examples do. my recollection of conventional wisdom is to avoid using cursors. is this difference merely a question of style, or is one approach right and the other wrong? oracle 8.1.7
7
2230
by: Philip Mette | last post by:
Does anyone have any good references they could recommend on Cursor based SQL writing? I have to create SQL that can loop though records simular to VB loops and I have been told that this is the way to go. Any recommendations would be helpful.
0
387
by: sblar | last post by:
In a stored procedure (SP1) I am looping through a cursor with records from Table1. Each record in the cursor is inserted into Table2. Insert trigger on Table2 is inserting the record into Table3 (in another DB). In the insert trigger on Table3, a series on checks are done on the inserted record and in case of an error, an email is sent and the trigger returns. This break the cursorloop in SP1 and the rest of the records in the cursor is...
4
1505
by: rawheiser | last post by:
Existing Stored Procedure, has been running well on SQL since 7.0. (but needed some tweaking to migrate to 2000). Now all of a sudden after installing SP4 of SQL 2000, this process slows down, and SQL Spotlight shows the number of locks just climbing throughout the processing run. According to the MS Knowledge Base Articles on KeyLocks .. this was a problem that was *fixed* in the service pack ... where as for me it is now broken.
0
11791
debasisdas
by: debasisdas | last post by:
SAMPLE CODE USING RECORD =========================== declare cursor c1 is select * from dept; type drec is record (a dept.deptno%type, b dept.dname%type, c dept.loc%type); type ttype is table of drec index by binary_integer; dr drec;
0
18041
debasisdas
by: debasisdas | last post by:
RESTRICTIONS ON CURSOR VARIABLES ================================= Currently, cursor variables are subject to the following restrictions: Cannot declare cursor variables in a package spec. CREATE PACKAGE emp_stuff AS TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE; emp_cv EmpCurTyp; -- not allowed END emp_stuff;
0
4676
debasisdas
by: debasisdas | last post by:
This thread contains some useful tips/samples regarding some advance concepts in cursors. FEW MORE EXAMPLES =================== declare er emp%rowtype; cursor c1 is select * from emp; begin open c1;
0
4862
debasisdas
by: debasisdas | last post by:
Sample example to show FOR UPDATE CURSOR ----------------------------------------------------------------------------- DECLARE CURSOR EMPREC IS SELECT * FROM EMP FOR UPDATE OF SAL; MYREC EMPREC%ROWTYPE; NUM NUMBER(4); BEGIN OPEN EMPREC; LOOP
0
8043
debasisdas
by: debasisdas | last post by:
Cursor Variable Returning %ROWTYPE ----------------------------------------------------------- DECLARE TYPE TmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE; tmp_cv TmpCurTyp;TYPE EmpCurTyp IS REF CURSOR RETURN tmp_cv%ROWTYPE; emp_cv EmpCurTyp; BEGIN NULL;
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10212
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10047
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9995
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.