Tuesday, February 14, 2012

Deallocating cursor if exception occured.

Hi all,
i am facing one problem while executing stored procedure.
What i am doing is i am opening one cursor and then depending on values
fetch inside the cursor i am inserting data into one table.
But sometimes my insert query failes due to violation in primary key.
In that case sp is not directly stopping its execution.
So my question is if such situation occured how will i deallocate my
cursor. I am using sql server 2000.
How to handle such exception to execute next part of stored procedure.
Thanks in advance.
trialproduct2004@.yahoo.com wrote:
> Hi all,
> i am facing one problem while executing stored procedure.
> What i am doing is i am opening one cursor and then depending on values
> fetch inside the cursor i am inserting data into one table.
>
I suggest you do that with a WHERE clause rather than a cursor.
INSERT INTO tbl1 (co1, col2, ...)
SELECT col1, col2, ...
FROM tbl2
WHERE ... ?

> But sometimes my insert query failes due to violation in primary key.
> In that case sp is not directly stopping its execution.
Ditto. Better to fix your code rather than handle the errors it causes.
Change your INSERT query to avoid inserting duplicate rows.
Cursors should be a last resort only. At least 99.9% of the time you
can and should avoid them.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx

No comments:

Post a Comment