查询是否要从中选择要作为表达式的数据的表名?

问题描述 投票:1回答: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;
sql sql-server sql-server-2014
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);
© www.soinside.com 2019 - 2024. All rights reserved.