一开始我们有这个——这很混乱。

为了稍微清理一下,我添加了两个视图和一个同义词:
create view v_Value as
select
ID as ValueID
, tb_modules_ID as ModuleID
, usertype_OR_religion_ID as RemoteID
from tb_value ;
go
create view v_Religion as
select
ID
, ReligionName as Title
from tb_religion ;
go
create synonym v_UserType for tb_UserType ;
go
现在模型看起来像

现在编写查询更容易了
;
with
q_mod as (
select
m.ID as ModuleID
, coalesce(x1.ID , x2.ID) as RemoteID
, coalesce(x1.Title , x2.Title) as Title
, m.Description as ModuleType
from tb_Modules as m
left join v_UserType as x1 on m.TableName = 'tb_UserType'
left join v_Religion as x2 on m.TableName = 'tb_Religion'
)
select
a.ModuleID
, v.ValueID
, a.RemoteID
, a.ModuleType
, a.Title
from q_mod as a
join v_Value as v on (v.ModuleID = a.ModuleID and v.RemoteID = a.RemoteID) ;
此查询有一个明显的模式,因此如果您必须添加另一个模块类型的表,可以将其创建为动态 sql。添加另一个表时,请使用ID
andTitle
以避免必须使用视图。
编辑
构建动态 sql(或在应用程序级别查询)
修改第 6 行和第 7 行,x-index 为tb_modules.id
coalesce(x1. , x2. , x3. ..)
向左连接添加行(第 11 行下方)
left join v_SomeName as x3 on m.TableName = 'tb_SomeName'
SomeName
is和tb_modules.description
x-index 匹配tb_modules.id
编辑 2
最简单的可能是将上述查询打包到一个视图中,然后每次模式更改时动态创建并运行ALTER VIEW
。这样查询就不会从应用程序的角度改变。