Monday, December 10, 2012

How to Create Cursor




declare @tempt table
(
ID int null,
Name varchar(100) null
)

DECLARE @vendor_id int, @vendor_name nvarchar(50),
    @message varchar(80), @product nvarchar(50);

PRINT '-------- Vendor Products Report --------';


-- Declare Cursor – untill it deallocate
-- You Con’t declare another cursor with same name.

DECLARE vendor_cursor CURSOR FOR
SELECT ID,Ag_Fname
from AgentMaster

OPEN vendor_cursor

FETCH NEXT FROM vendor_cursor
INTO @vendor_id, @vendor_name

WHILE @@FETCH_STATUS = 0
BEGIN
   
    SELECT @message = '----- Vendor: ' +
        @vendor_name

    PRINT @message
    insert INTO @tempt values (@vendor_id, @vendor_name)
   
    FETCH NEXT FROM vendor_cursor
    INTO @vendor_id, @vendor_name
END
CLOSE vendor_cursor;

select * from @tempt
-- Deallocate Cursor
DEALLOCATE vendor_cursor;

No comments:

SQL Optimization

  SQL Optimization  1. Add where on your query  2. If you remove some data after the data return then remove the remove condition in the sel...