17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Appendix A: System Functions<br />

@@FETCH_STATUS<br />

Returns an indicator of the status of the last cursor FETCH operation.<br />

If you’re using cursors, you’re going to be using @@FETCH_STATUS. This one is how you know the success or<br />

failure of your attempt to navigate to a record in your cursor. It will return a constant depending on whether<br />

<strong>SQL</strong> <strong>Server</strong> succeeded in your last FETCH operation or not, and, if the FETCH failed, why. The constants are:<br />

❑ 0 — Success<br />

❑ -1 — Failed. Usually because you are beyond either the beginning or end of the cursorset.<br />

❑ -2 — Failed. The row you were fetching wasn’t found, usually because it was deleted between<br />

the time when the cursorset was created and when you navigated to the current row. Should<br />

only occur in scrollable, non-dynamic cursors.<br />

For purposes of readability, I often will set up some constants prior to using @@FETCH_STATUS.<br />

For example:<br />

DECLARE @NOTFOUND int<br />

DECLARE @BEGINEND int<br />

SELECT @NOTFOUND = -2<br />

SELECT @BEGINEND = -1<br />

I can then use these in my conditional in the WHILE statement of my cursor loop instead of just the row<br />

integer. This can make the code quite a bit more readable.<br />

CURSOR_STATUS<br />

604<br />

The CURSOR_STATUS function allows the caller of a stored procedure to determine if that procedure has<br />

returned a cursor and result set. The syntax is as follows:<br />

CURSOR_STATUS<br />

(<br />

{‘’, ‘’}<br />

| {‘, ‘’}<br />

| {‘’, ‘’}<br />

)<br />

local, global, and variable all specify constants that indicate the source of the cursor. local equates<br />

to a local cursor name, global to a global cursor name, and variable to a local variable.<br />

If you are using the cursor name form then there are four possible return values:<br />

❑ 1 — The cursor is open. If the cursor is dynamic, its result set has zero or more rows. If the cursor<br />

is not dynamic, it has one or more rows.<br />

❑ 0 — The result set of the cursor is empty.<br />

❑ -1 — The cursor is closed.<br />

❑ –3 — A cursor of cursor name does not exist.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!