• You could generate the detach statements via a query such as the following:

    select 'EXEC sp_detach_db ' + '''' + name + ''''

    from sys.databases

    where name like '%dbname%'

    The sp_attach_db statements (or create database .. for attach) can be generated in a similar way but you may need to take account of files that need to be put in different locations when they get attached