Thursday, 22 March 2012

(SQL SERVER) SIMPLE EXAMPLE OF USING A CURSOR


The below example explains the retrieval of column values in single column separated by commas.

  
DECLARE Holiday CURSOR FOR
SELECT HolidayName FROM HolidayMaster

DECLARE @HolidayName NVARCHAR(MAX),
            @Output NVARCHAR(MAX)

SET @Output = ''

OPEN Holiday
FETCH NEXT FROM Holiday INTO @HolidayName
WHILE @@FETCH_STATUS = 0
BEGIN
 SET @Output = @Output + '' + @HolidayName + ','
 FETCH NEXT FROM Holiday INTO @HolidayName
END

--To remove the comma at the end
SET @Output = SUBSTRING(@Output, 0, LEN(@Output))

CLOSE Holiday
DEALLOCATE Holiday
SELECT @Output AS Output

OUTPUT



No comments:

Post a Comment