我使用的是 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;