Recently, I discovered a job running on an instance of SQL Server (not a production server, test server mercifully!) that ran this:

SET NOCOUNT ON
EXECUTE master.sys.sp_MSforeachdb'
declare @sql nvarchar (max)
USE [?] IF DB_ID(''?'') > 4
BEGIN
declare @snapshot INT
select @snapshot = source_database_id from master.sys.databases where database_id = DB_ID(''?'')
IF @snapshot IS NULL
BEGIN
with cteLogType (logname, logfile)
as
(
select name, right (sf.filename,3) from ?.dbo.sysfiles sf
)
select @sql = ''
use [?]
dbcc shrinkfile (''+logname+'',1)
USE [master]
ALTER DATABASE [?] MODIFY FILE ( NAME =''+logname+'', FILEGROWTH = 1%)''
from cteLogType
where logfile = ''ldf''
END
END
exec (@sql)'
SET NOCOUNT OFF

I don’t quite know how I feel about this script. On a test server it’s great but at the same time it’s so wrong.

Are there any scripts or code you’ve seen written which you love and hate at the same time? Share your pieces below!