SQL Server sqlcmd setvar depending of selected database
You cannot mix sqlcmd mode commands with T-SQL conditional logic.  There is a way to do this, but as to whether it is advisable is another matter.

This technique involves redirecting stdout, writing out to a file and executing that file all under sqlcmd mode to get the effect you require:

:out d:\temp\temp.sql
go

declare @x varchar(5) = 'dev'

if @x = 'dev'
    print ':setvar testVar dev'
else if @x = 'prod'
    print ':setvar testVar prod'
else raiserror( 'Unknown value (%s) for sqlcmd variable testVar.', 16, 1, @x )
go
:out stdout
go

!!REM Read the file to execute the setvar statement
:r d:\temp\temp.sql
go

select '$(testVar)' env

print 'it looks like this is the $(testvar) environment after all'
go


Obviously the process running this will require access to a scratch directory and file, and there are associated permissions (and risks) with this method.  The placement of GOs is important when redirecting output.

As regards usage, I would not particularly advise it.  We experimented with this (hence I know this technique) but moved away from it in favour of either database projects (which handle all this for you) or re-runnable (idempotent) scripts.  Rather than have a load of conditional logic in parent scripts, each object script was built to be re-runnable using 'if not exists' checks, for example:

if not exists ( the table )
  create the table

if not exists ( a column )
  add the column


Then it didn't matter if we were running in dev or prod, or how many times we ran the script.  These can get a bit unwieldy after a time.