Question

I want to use an SQL table like an .ini file

so :

 select answer from x where (y=z)  
 if exists 
  {
   return answer (from databse)
  }
else
 {   
   insert into x, (answer) where (y=z)  
   return answer (from default)
 }

Where answer is a default value, that may be changed by the query.

I would like to do this in one query if possible, I can do it in two, but I feel sure there is a more elegant method.

Was it helpful?

Solution

Assuming table c has the currently configured value and table d contains the system defaults

both with fields key (unique constraint) and val

I can use a union query to look up values

select top 1 * from ( 
  select 'c' source, key, val from c
  union all 
  select 'd', key, val from d
) x
where key = 'something'
order by source

this will return the configured value if it exists or the default if it does not. I kind of agree with @bohemian - not sure I see the point of the insert, if the default value is changed then the query will still work.

If you really want to do the insert maybe look at rolling out a stored proc.

OTHER TIPS

Not sure, why your mixing DML with your select as mentioned by @Bohemian but on select part you can do something like below

select
case 
when exists(select answer from x where y=z) then answer
else (select answer from default) as answer
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top