Accepts variables and procedure parameters for the row number arguments to the ABSOLUTE and RELATIVE keywords.
For additional syntax information for the FETCH statement, see the Microsoft SQL Server Transact-SQL Reference.
FETCH [[NEXT | PRIOR | FIRST | LAST
| ABSOLUTE {n | @nvar} | RELATIVE {n | @nvar}]
FROM] cursor_name
[INTO @variable_name1, @variable_name2, ...]
where
This statement retrieves a specific row from the cursor. Variables can be used for row number arguments. For example, the FETCH ABSOLUTE statement can be used with a variable to find a particular row within the cursor. For example, the row this statement retrieves depends upon the value of the @row_num variable:
FETCH ABSOLUTE @row_num FROM customer_cursor
By using variables for row number argument names, the program can provide the value at run time. This is useful because the row number value can be dependent upon run-time data that is available only at run time. This offers greater flexibility for programming the FETCH statement.
This example calculates the median number of personnel in the various departments of a specific company. The company name is specified in the procedure. To calculate the median number of employees in a specific department, follow these steps:
For this example, assume that a database exists that holds all departments' populations for all companies in the Algodata Infosystems conglomerate.
/*Create procedure*/ CREATE PROCEDURE find_median_population @company varchar(25) AS DECLARE @num_departments int DECLARE @value1 int DECLARE @value2 int DECLARE @middle int /* Declare cursor on population table */ DECLARE population_cursor SCROLL CURSOR FOR select population FROM population_table WHERE company = @company ORDER BY population OPEN population_cursor SELECT @num_departments=@@cursor_rows SELECT @middle=@num_departments /2 IF (@num_departments % 2)=0 BEGIN FETCH ABSOLUTE @middle FROM population_cursor INTO @value1 FETCH NEXT FROM population_cursor INTO @value2 SELECT "Company population median for " + @company + " is: " + CONVERT(char(10), (@value1 + @value2) / 2) END ELSE BEGIN SELECT @middle = @middle + 1 FETCH ABSOLUTE @middle FROM population_cursor INTO @value1 SELECT "Company population median for " + @company + " is: " + CONVERT(char(10), @value1) END CLOSE population_cursor DEALLOCATE population_cursor
The find_median_population stored procedure can be executed in these ways:
EXECUTE find_median_population 'New Moon Books' EXECUTE find_median_population 'Five Lakes Publishing' EXECUTE find_median_population 'Scootney Books'