@bobnoordam

SqlServer: Detecting and acting based on the active database

Detecting and acting on the database name to change query behaviour for example for different company workflows within the same database. This is BRITTLE because database names can change outside your application. The safe way to handle this is by checking some flag to determine correct processing.



-- Select one column, which contains a 1 'if database'
select 
	case when db_name() = 'database1' then 1 end


-- Select one column, which contains a 1 or 2 value depending on 'database or not'
select
	case when db_name() = 'database1' then 1 else 2 end


-- Generate two columns, one has output depending on 'if database'
select
	coalesce(case when db_name() = 'database1' then 1 end, 0),
	coalesce(case when db_name() = 'database2' then 2 end, 0)