IF doesn't work that way. It tests a condition and executes or skips the statement after it based on that condition.
You'll be better of building a cursor and having it step through sys.databases and execute a dynamic SQL command for each.
declare DBs cursor local fast_forward for
select name
from sys.databases
where ID > 4; -- Or modify the Where clause to fit your scenario
open DBs;
declare @DB nvarchar(100), @SQL nvarchar(max);
fetch next from DBs into @DB;
while @@fetch_status = 0
begin
select @SQL = 'select top 1 ''' + @DB + ''', versionname from [' + @DB + '].dbo.databaseversion order by versionID desc;';
print @SQL;
exec (@SQL)
fetch next from DBs into @DB;
end;
close DBs;
deallocate DBs;
Try something like that, see if it will do what you need.
I would suggest changing the simple select statement to an insert select into a temp table, then select from that at the end after the cursor is done. Usually ends up being easier to read/use.
- Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
Property of The Thread
"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon