You can use a cursor for the task:
declare cur cursor for
select name
from sys.sysdatabases
where crdate <= DATEADD(month, -6, GETDATE())
and name not in ('master','model','msdb','tempdb','distribution')
declare @name nvarchar(200)
open cur
fetch next from cur into @name
while @@FETCH_STATUS = 0
begin
EXEC master.dbo.sp_detach_db @dbname = @name, @keepfulltextindexfile = N'true'
fetch next from cur into @name
end
close cur
deallocate cur