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

Comments

Popular posts from this blog

System.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out

Pre login Handshake or Connection Timeout Period

Transparent Data Encryption(TDE) with Master Key and Certificate in SQL Server