Today was working on SQL Server cursor
standard cursor deification would be like this:
sqlcursor from (Azure Data Studio)
———————————————————————————————————————–
— Declare a cursor for a Table or a View ‘TableOrViewName’ in schema ‘dbo’
DECLARE @ColumnName1 NVARCHAR(50), @ColumnName2 NVARCHAR(50)
DECLARE db_cursor CURSOR FOR
SELECT name FROM dbo.TableOrViewName
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @ColumnName1, @ColumnName2
WHILE @@FETCH_STATUS = 0
BEGIN
— add instructions to be executed for every rows
SELECT @db_nm
FETCH NEXT FROM db_cursor INTO Sys.Databases
END
CLOSE db_cursor
DEALLOCATE db_cursor
GO
———————————————————————————————————————–
but when you want to run the “SELECT xxx” with if you want to run a cursor with passing the variable(db_name) and if you pass the db_name run the cursor for that variable else run for all the databases.
so when you try to declare cursorif (@db_nm is null)
select @SQL=convert(nvarchar(250),’SELECT name FROM Sys.Databases’)
else
Select @SQL=convert(nvarchar(250),’SELECT name FROM Sys.Databases where name =”’+@db_nm+””)
This will give an error:
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near ‘@SQL’.
———————————————————————————————————————-
—-This is the Correct way and solution for it. hope this helps.
DECLARE @db_nm varchar(20)
DECLARE @SQL nvarchar(1024)
if (@db_nm is null)
select @SQL=N’DECLARE allDB_cursor CURSOR FOR SELECT name FROM Sys.Databases’
else
Select @SQL=convert(nvarchar(250),’DECLARE allDB_cursor CURSOR FOR SELECT name FROM Sys.Databases where name =”’+@db_nm+””)
EXEC (@SQL)
OPEN allDB_cursor
FETCH NEXT FROM allDB_cursor INTO @db_nm
WHILE @@FETCH_STATUS = 0
BEGIN
print @db_nm
FETCH NEXT FROM allDB_cursor INTO @db_nm
END
CLOSE allDB_cursor
DEALLOCATE allDB_cursor
GO