我正在使用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;
答案 0 :(得分: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)