Cursorless Cursor

,

Here is as sample of implementing cursor.
In some cases my tests showed that this approach performs better than native cursors in SQL Server.
All you have to do is move the dataset into a temp table with a new Identity column and then use a simple loop to extract the data as you would do normally in a cursor.
The major downside of this approach is using it with a large table.
There are couple of ways to create a temp table, you can do it with SELECT INTO, INSERT INTO, Table variable in SQL 2000.
Again each one of theese methods has it's own disadvantages based on the task, with Insert into table has to be created before the data is moved.
Bellow is an example of SELECT INTO implementation

/*Create temporary table using SELECT INTO statement*/
DECLARE @I as int,
	@Row_Count int,
	@au_id char(11),
	@au_lname varchar(50),
	@au_fname varchar(50),
	@phone varchar(15)

SET @I = 1

SET NOCOUNT ON
SELECT 	
	IDENTITY(int, 1,1) AS ID_Num,
	au_id, 	au_lname, au_fname, phone
INTO #TempTable  FROM authors

SET @Row_Count = (SELECT COUNT(*) FROM #TempTable)

WHILE @I <= @Row_Count 
	BEGIN
/*Simulate fetch statement*/
	SELECT @au_id = au_id, @au_lname = au_lname, 
		@au_fname = au_fname, @phone = phone 
	FROM #TempTable WHERE ID_Num = @I
/*Show the result*/
	SELECT  @au_id AS [AuthorID], @au_lname AS LastName, 
		@au_fname AS FirstName, @phone AS Phone

		SET @I = @I + 1
	END
DROP TABLE #TempTable
SET NOCOUNT OFF
GO

Rate

4.5 (2)

Share

Share

Rate

4.5 (2)