How to combine 2 SQL statements into one? I have these 2 SQL statements. Each year, I need to add the new one for the new DB. How can I write it so it will just work for the new years instead of me manually editing this each year? Is there a way ONE will work for all? Each years will have 'CTX_' in it. thanks

USE CTX_2015

DBCC SHRINKFILE(ctx_2015_log)
BACKUP LOG ctx_2015 TO DISK='NUL:'
DBCC SHRINKFILE(ctx_2015_log)


USE CTX_2016

DBCC SHRINKFILE(ctx_2016_log)
BACKUP LOG ctx_2016 TO DISK='NUL:'
DBCC SHRINKFILE(ctx_2016_log)
A quick and dirty way would be to have a script for the next X years.
Something like:

IF db_id('ctx_2015_log') is not null
EXECUTE('
BEGIN
    USE select quotename(db_name(db_id(''ctx_2015_log'')))
    DBCC SHRINKFILE(ctx_2015_log)
    BACKUP LOG ctx_2015 TO DISK=''NUL:''
    DBCC SHRINKFILE(ctx_2015_log)
END
');

IF db_id('ctx_2016_log') is not null
EXECUTE('
BEGIN
    USE select quotename(db_name(db_id(''ctx_2016_log'')))
    DBCC SHRINKFILE(ctx_2016_log)
    BACKUP LOG ctx_2016 TO DISK=''NUL:''
    DBCC SHRINKFILE(ctx_2016_log)
END
');


You can build this statement with: 

DECLARE @i int =2015
DECLARE @ti varchar (4)
DECLARE @command varchar (max)

WHILE @i&lt;2020
BEGIN
    SET @ti=CONVERT(varchar(4), (@i))
    SET @command=
        'IF db_id(''ctx_'+@ti+'_log'') is not null
        EXECUTE(''
        BEGIN
            USE select quotename(db_name(db_id(''''ctx_'+@ti+'_log'''')))
            DBCC SHRINKFILE(ctx_'+@ti+'_log)
            BACKUP LOG ctx_'+@ti+' TO DISK=''''NUL:''''
            DBCC SHRINKFILE(ctx_'+@ti+'_log)
        END
        '');
        '
    PRINT @command
    SET @i+=1
END