Creating a SQL view based on a column value

时间:2017-05-16 09:18:37

标签: sql sql-server sql-server-2014 sql-view

I have two tables, one is titled 'Shop' and the other is 'GlobalSettings'. 'GlobalSettings' and 'Shop' contain a few identical columns. The idea is to allow the user to save 'Shop' level settings but also allow them to override them via the 'GlobalSettings'. I'm attempting to create a view that outputs the correct columns based on a true/false field on 'GlobalSettings' called 'OverrideSettings'.

If 'OverrideSettings' is true then output the columns used in 'GlobalSettings' otherwise output the columns in 'Shop'.

Can this be done with a view?

Any help would be great, Thanks

2 个答案:

答案 0 :(得分:0)

Join the tables and use CASE WHEN in your SELECT (CASE WHEN OverrideSettings=1 THEN value from OverrideSettings ELSE value from GlobalSettings END AS Col

I have made some assumptions as to the data model below, but you should get the general idea, I hope:

Select CASE WHEN gs.overridesettings=1 THEN gs.val1 ELSE s.val1 END
FROM shop AS s
LEFT OUTER JOIN globalsettings AS gs
 ON gs.ShopId = s.ShopId
 AND s.col1 = gs.col1

答案 1 :(得分:0)

 CREATE VIEW v AS
 Select a.col1,a.col2,a.col3
 from shop a inner join globalsettings b on a.col1=b.col1 --Join as per  matching cols
 where b.overridesettings=false
  union
 select col1,col2,col3
 from globalsettings  where overridesettings=true

Or

CREATE VIEW v AS
Select Case when b.overridesettings=false Then a.col1 else b.col1 end,
       Case when b.overridesettings=false Then a.col2 else b.col2 end ,
       Case when b.overridesettings=false Then a.col3 else b.col3 end
from shop a 
inner join globalsettings b
on a.col1=b.col1 --Join as per matching cols