1

我使用的是 SQL Server 12.2.9 版(我认为是 SQL Server 2014)?

在 SQL 查询中,是否可以有一个或多个要从中选择数据的表名,作为将在查询执行期间评估的表达式?例如在下面的伪代码中?

SELECT * 
FROM MainTable AS mainTable, 
(
  /* Expression here that returns 
     a string (or what type do we return) 
     denoting the other table name 
  */ 
) AS AliasFoo
WHERE AliasFoo.Id = mainTable.ExternalId;

您能否提供此类查询的样本?具体来说,我们从应该返回对表/表名的引用的表达式返回什么数据类型?

问题的进一步发展

为了使这个例子更具体一点,以邀请适当的帮助,这里是一个人为的例子。

假设我有以下表格:

ActivityType
---------
Id ( int primary key, identity )
ActivityName (possible values are 'Jogging', 'Biking', and more)

ActivityLog
--------
Id ( int, primary key, identity) 
DateTime
ActivityTypeId
ActivityDetailId (a primary key of one of the following activity detail tables)

ACTIVITY DETAIL TABLES

Jogging
--------
Id ( int, primary key, identity) 
WhoWasJogging
ForHowLong
WhatShoesWereTheyWearing

Biking
--------
Id ( int, primary key, identity) 
WhoWasBiking
WhatBikeWasThat
WhatBrand
Color
Speed
ForHowLong

鉴于上述表格,我可以有这样的查询吗?

SELECT aLog.DateTime, aType.ActivityName, activityDetail.*
FROM ActivityLog AS aLog, ActivityType AS aType, 
(
  /*
  if ActivityType.ActivityName == 'Jogging' then the 'Jogging' table, 
  else if ActivityType.ActivityName == 'Biking' then the 'Biking' table
  */
) AS activityDetail
WHERE aLog.ActivityTypeId = aType.Id
AND activityDetail.Id = aLog.ActivityDetailId;
4

1 回答 1

1

好的,这是否是最佳答案取决于您在现实世界中有多少不同的表。因此,对于少量表left joining是一种可能的解决方案,如下所示。您可以看到这增加了选择列的复杂性,但这可能会满足您的需求。

select aLog.[DateTime]
  , aType.ActivityName
  , case when aType.ActivityName = 'Jogging' then J.WhoWasJogging else B.WhoWasBiking end WhoWas
  -- And so on
from ActivityLog as aLog
inner join ActivityType as aType on aType.Id = aLog.ActivityTypeId
left join Jogging as J on aType.ActivityName = 'Jogging' and aLog.ActivityDetailId = J.Id
left join Biking as B on aType.ActivityName = 'Biking' and aLog.ActivityDetailId = B.Id

它还取决于您是否要一次查询多个活动类型。

如果首选动态 SQL,那么以下应该可以工作:

declare @Sql nvarchar(max), @Activity varchar(128) = 'Biking';

set @Sql = 'select aLog.[DateTime]
  , aType.ActivityName
  , A.*
from ActivityLog as aLog
inner join ActivityType as aType on aType.Id = aLog.ActivityTypeId
inner join ' + @Activity + ' as A on and aLog.ActivityDetailId = A.Id
where aType.ActivityName = ''' + @Activity + '''';

exec (@sql);
于 2019-02-21T03:13:42.523 回答