由于脚本中使用了CONCAT函数,该函数是TSQL在SQL Server 2012中新引入的函数,具体详见:https://docs.microsoft.com/en-us/sql/t-sql/functions/concat-transact-sql。
因此如果想在SQL Server 2012以下版本中使用的话需要把CONCAT函数改成string +方法,具体如下:
-- Created by Bob from
use master
DECLARE dbCursor CURSOR for select name from [master].[sys].[databases] where state = 0 and is_in_standby = 0;
DECLARE @dbname NVARCHAR(255)
DECLARE @recoveryModel NVARCHAR(255)
DECLARE @tempTSQL NVARCHAR(255)
DECLARE @dbFilesCursor CURSOR
DECLARE @dbFile NVARCHAR(255)
DECLARE @flag BIT
OPEN dbCursor
FETCH NEXT FROM dbCursor INTO @dbname
WHILE @@FETCH_STATUS = 0
BEGIN
if((@dbname <> 'master') and (@dbname <> 'model') and (@dbname <> 'msdb') and (@dbname <> 'tempdb') and (@dbname <> 'Resource'))
begin
print('')
print('Database [' + @dbname + '] will be shrinked log...')
SET @flag = 1
SET @recoveryModel = (SELECT recovery_model_desc FROM sys.databases WHERE name = @dbname)
if((@recoveryModel = 'FULL') or (@recoveryModel = 'BULK_LOGGED'))
begin
SET @tempTSQL = ('ALTER DATABASE [' + @dbname + '] SET RECOVERY SIMPLE with no_wait')
EXEC sp_executesql @tempTSQL
if (@@ERROR = 0)
begin
print(' Database [' + @dbname + '] recovery model has been changed to ''SIMPLE''.')
SET @flag = 1
end
else
begin
print('Database [' + @dbname + '] recovery model failed to be changed to ''SIMPLE''.')
SET @flag = 0
end
end
if(@flag = 1)
begin
SET @tempTSQL = ('use [' + @dbname + ']')
EXEC sp_executesql @tempTSQL
SET @dbFilesCursor = CURSOR for select sys.master_files.name from sys.master_files, [master].[sys].[databases] where databases.name = @dbname and databases.database_id = sys.master_files.database_id
open @dbFilesCursor
FETCH NEXT FROM @dbFilesCursor INTO @dbFile
WHILE @@FETCH_STATUS = 0
BEGIN
SET @tempTSQL = ('use [' + @dbname + '] DBCC SHRINKFILE (N''' + @dbFile + ''') with NO_INFOMSGS')
EXEC sp_executesql @tempTSQL
if(@@ERROR = 0) print(' Database file [' + @dbFile + '] has been shrinked log successfully.')
FETCH NEXT FROM @dbFilesCursor INTO @dbFile
END
CLOSE @dbFilesCursor
DEALLOCATE @dbFilesCursor