What I'm getting at is something like this... (Assume VB.Net)
dim conPubs as SQLConnection
dim strSelect as String
dim dbname as String
dim cmdSelect as SqlCommand
<embed your logic to decide what the dbname should be here>
conPubs = New SqlConnection ( "server=localhost;UID=sauser;PWD=sauser123!#;Database=Pubs )
strSelect = "exec @dbname.dbo.functionname()"
cmdSelect = New SqlCommand( strSelect, conPubs )
cmdSelect.Parameters.Add( "@dbname", <object where you stored the dbname>)
conPubs.Open()
blah, blah, blah.
Does that help?