SAF(NET) = STEPHEN A. FUQUA operating on the Web since 1995

Stephen is a web developer, Bahá'í, and interfaith activist in St. Paul, Minnesota. He likes to write about religion, social justice, sustainability, science, programming, &c.

June 2009 Archives

Closing A Cursor in SQL Catch

|

Problem: In a T-SQL script, an exception occurs while a cursor is open, resulting in the cursor never being closed. But, the exception handling wraps the entire script, not just the cursor, so there is no guarantee that the cursor will be open if/when the CATCH statement is reached.

Solution: query the sys.syscursors view to see if the cursor(s) in question is still open:

BEGIN CATCH
     ...

     IF EXISTS (SELECT 1 FROM sys.syscursors WHERE cursor_name = 'MyCursor')
     BEGIN
	DEALLOCATE MyCursor
     END
     
     ...
END CATCH

Update 7/14/09

I just tried to deploy this to a development environment, rather than my own computer. There it was running as a user with restricted access. I received the following error:The SELECT permission was denied on the object 'syscursors', database 'mssqlsystemresource', schema 'sys'."

This was easily remedied when I finally discovered the CURSOR_STATUS function:

DECLARE @cursorstatus int;
SELECT @cursorstatus = cursor_status('global','MyCursor')
IF @cursorstatus > -2
BEGIN
	DEALLOCATE MyCursor
END

Think For One ... Second

| | Comments (0)

What’s wrong with this code? There are unnecessary lines. So? Why care about unnecessary lines? Because it shows that the programmer was not really thinking about what he was doing.

        MyObject obj = someList.Find(delegate(MyObject test)
        {
            if (test.Id.Equals(packageId))
            {
                return true;
            }
            else
            {
                return false;
            }
        });

deprecated

On safnet.com

Other sites managed or developed by S.A.F.

S.A.F. elsewhere on the web

  • LinkedIn
    LinkedIn can actually be useful when looking for prospective hires and business or organizational partners
  • GoodReads
    A fun and relatively-unknown social networking site geared towards one's book list
  • Live Journal
    Mirror of the blog at safnet.com, so that a few LJ friends can more easily read and comment there