Monday, October 8, 2012

Cursors in SQL Server 2005

Cursors in SQL server are very usefull for updating table.using row by row operations.cursors are like loop in other programming language. we can create cursors very easily.

I will show the scenario where cursors are usefull.If we have have a test_cursors table where we have only districtnames and we want to be update the DistrictId columns with respective to the districtname.and we have district master table where we have correspond Districtname and districtId columns.Suppose we have 100 Different Districtnames for updating ,then we want to write 100 update statements.Instead of check district id and update DistrictId for the proper district we can use Cursors.
Instead of writing multiple statements cursors allows you to update total records sets using fetching rows and updating each row.

There are four basic steps for creating cursors.

First we need to declare cursor.

Declare Cursor(cursorname).

Then after declaring cursor then

open the Cursor(cursorname).

Third step is Fetching the cursor to getting the data.

Fetch cursor(cursor)


BEGIN
	DECLARE @dist VARCHAR(50);
	DECLARE @distcode INT

	DECLARE c_master CURSOR LOCAL FAST_FORWARD
	FOR
	SELECT DISTINCT Districtname
	FROM dbo.test_cursors

	OPEN c_master

	FETCH c_master
	INTO @dist

	WHILE (@@fetch_status != - 1)
	BEGIN
		SELECT @distcode = (
				SELECT districtid
				FROM masterdata.hihlmain.district
				WHERE Districtname = @dist
				)

		UPDATE dbo.test_cursors
		SET Districtid = @distcode
		WHERE Districtname = @dist

		FETCH c_master
		INTO @dist
	END

	CLOSE c_master

	DEALLOCATE c_master
END

No comments: