Cursor Vs IF and While
Here i am writing a query which gives the all the databases from sys.databases
I have written this query using Cursor and While Loops
---Using Cursor
DECLARE MyCursor CURSOR
FOR
SELECT [Name]FROM SYS.DATABASES
OPEN MyCursor
FETCH NEXT FROM MyCursor
WHILE @@FETCH_STATUS =0
FETCH NEXT FROM MyCursor
CLOSE MyCursor
DEALLOCATE MyCursor
---Using While Loop
DECLARE @Databases sysname
DECLARE @Count INT
SET @Count= (SELECT COUNT (*)FROM SYS.DATABASES)
--PRINT @Count
IF @Count > 0
BEGIN
WHILE(@Count>0)
BEGIN
WITH CTE
AS
(
SELECT ROW_NUMBER()OVER (ORDER BY([Name]))as RowNumber,[Name]
FROM SYS.DATABASES
)
SELECT @Databases=[Name]
FROM CTE
WHERE RowNumber=@Count
SET @Count=@Count-1
SELECT @Databases as Databases
END
END
go
I have written this query using Cursor and While Loops
---Using Cursor
DECLARE MyCursor CURSOR
FOR
SELECT [Name]FROM SYS.DATABASES
OPEN MyCursor
FETCH NEXT FROM MyCursor
WHILE @@FETCH_STATUS =0
FETCH NEXT FROM MyCursor
CLOSE MyCursor
DEALLOCATE MyCursor
---Using While Loop
DECLARE @Databases sysname
DECLARE @Count INT
SET @Count= (SELECT COUNT (*)FROM SYS.DATABASES)
--PRINT @Count
IF @Count > 0
BEGIN
WHILE(@Count>0)
BEGIN
WITH CTE
AS
(
SELECT ROW_NUMBER()OVER (ORDER BY([Name]))as RowNumber,[Name]
FROM SYS.DATABASES
)
SELECT @Databases=[Name]
FROM CTE
WHERE RowNumber=@Count
SET @Count=@Count-1
SELECT @Databases as Databases
END
END
go
Comments