title: Conditional select on view
body: <p>I have a view in my database (<code>MSSQL</code>) that takes more than 1 minute to output results. Since this is taking this long, I gave the user the ability to either see live data or cached data. I do this by generating the data from the view and inserting it into a table hourly and by defining a config variable on use_cached = 0 or 1.</p>
  
  <p>Lets say the view is called v_foo and the cache table is called t_bar. I want to create another view that selects from v_foo if <code>use_cached = 0</code> and select from t_bar if <code>use_cached = 1.</code></p>
  
  <p>I tried something like</p>
  
  <pre><code>Create view v_final as 
  select * from v_foo
  where (select count(*) from config where id = 'use_cache' and value = 1) = 0
  UNION ALL
  select * from t_bar
  where (select count(*) from config where id = 'use_cache' and value = 1) = 1
  </code></pre>
  
  <p>But this causes both queries from the union all to be always calculated even if one of them does not return any rows.
  Using a function is also a not so good solution because in order to return a table using IF conditions, I must declare a temporary table and just populating it is taking almost 17 seconds.</p>
  
  <p>Any Help?</p>