Skip to main content
deleted 25 characters in body
Source Link
user179264
user179264

You should make a couple ofsmall changes in your script

First change the type of @SQL to nvarchar and replaceReplace EXEC @SQL with EXEC sp_executesql @SQL or EXEC (@SQL) This works fine

DECLARE @DBName VARCHAR (64)
DECLARE @SQL NVARCHARVARCHAR (256) 
DECLARE DROPDB CURSOR FOR 
SELECT name FROM sys.databases 
WHERE create_date  <= '20190726' 
AND name NOT IN ('master','model','msdb','tempdb','distribution','ReportServer','ReportServerTempDB')

OPEN DROPDB
FETCH next FROM DROPDB INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @SQL = 'DROP DATABASE ' + @DBName
            PRINT @SQL
    EXEC sp_executesql @SQL --OR EXEC (@SQL)
    FETCH next FROM DROPDB INTO @DBName
END
CLOSE DROPDB
DEALLOCATE DROPDB

You should make a couple of changes in your script

First change the type of @SQL to nvarchar and replace EXEC @SQL with EXEC sp_executesql @SQL or EXEC (@SQL) This works fine

DECLARE @DBName VARCHAR (64)
DECLARE @SQL NVARCHAR (256)
DECLARE DROPDB CURSOR FOR 
SELECT name FROM sys.databases 
WHERE create_date  <= '20190726' 
AND name NOT IN ('master','model','msdb','tempdb','distribution','ReportServer','ReportServerTempDB')

OPEN DROPDB
FETCH next FROM DROPDB INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @SQL = 'DROP DATABASE ' + @DBName
            PRINT @SQL
    EXEC sp_executesql @SQL --OR EXEC (@SQL)
    FETCH next FROM DROPDB INTO @DBName
END
CLOSE DROPDB
DEALLOCATE DROPDB

You should make a small changes in your script

Replace EXEC @SQL with EXEC sp_executesql @SQL or EXEC (@SQL) This works fine

DECLARE @DBName VARCHAR (64)
DECLARE @SQL VARCHAR (256) 
DECLARE DROPDB CURSOR FOR 
SELECT name FROM sys.databases 
WHERE create_date  <= '20190726' 
AND name NOT IN ('master','model','msdb','tempdb','distribution','ReportServer','ReportServerTempDB')

OPEN DROPDB
FETCH next FROM DROPDB INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @SQL = 'DROP DATABASE ' + @DBName
            PRINT @SQL
    EXEC sp_executesql @SQL --OR EXEC (@SQL)
    FETCH next FROM DROPDB INTO @DBName
END
CLOSE DROPDB
DEALLOCATE DROPDB
Source Link
user179264
user179264

You should make a couple of changes in your script

First change the type of @SQL to nvarchar and replace EXEC @SQL with EXEC sp_executesql @SQL or EXEC (@SQL) This works fine

DECLARE @DBName VARCHAR (64)
DECLARE @SQL NVARCHAR (256)
DECLARE DROPDB CURSOR FOR 
SELECT name FROM sys.databases 
WHERE create_date  <= '20190726' 
AND name NOT IN ('master','model','msdb','tempdb','distribution','ReportServer','ReportServerTempDB')

OPEN DROPDB
FETCH next FROM DROPDB INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @SQL = 'DROP DATABASE ' + @DBName
            PRINT @SQL
    EXEC sp_executesql @SQL --OR EXEC (@SQL)
    FETCH next FROM DROPDB INTO @DBName
END
CLOSE DROPDB
DEALLOCATE DROPDB