Dynamically change a db in transact sql
You will want to use dynamic SQL to change the DB you are executing the query in:

DECLARE @dbname AS VARCHAR(100)
DECLARE @query AS VARCHAR(MAX)

SELECT @dbname = name
FROM sys.databases d
WHERE /*enter criteria here to get DB*/

SET @query = '
use ' + @dbname + '
/*enter your query here*/
'

PRINT @query
EXEC(@query)