2015-11-04 55 views
0

*注意:这与“可能的重复”不一样。在这里,对于在SELECT语句中返回的每个记录,表名将是不同的。所以我不能“设置”像set @tableName = 'whatever'这样的变量。如何在连接中使用select语句中返回的表名?

这是我的SQL - 看看我最后的内部连接。表中的e.Name EmailSendDefintion是我需要加入的表的名称。所以,这是一种动态的,我知道,但我如何加入存储在另一个表中的字段中的表?

select top 5000 
    x.HL_ACCT_ID as 'HL_ACCT_ID', 
    x.SALE_CODE as 'SALE_CODE', 
    s.SubscriberKey as 'EmailAddress', 
    o.EventDate as 'Opened', 
    c.EventDate as 'Clicked', 
    b.EventDate as 'Bounced' 
    from c100._sent s with (nolock) 
    inner join c100._job j with (nolock) on s.jobid = j.jobid 
    inner join emailsenddefinition e with (nolock) on e.customerkey = j.emailsenddefinition 
    left join c100._open o with (nolock) on o.jobid = s.jobid and o.subscriberkey = s.subscriberkey 
    left join c100._click c with (nolock) on c.jobid = s.jobid and c.subscriberkey = s.subscriberkey 
    left join c100._bounce b with (nolock) on b.jobid = s.jobid and b.subscriberkey = s.subscriberkey 
inner join c100.[e.name] x with (nolock) on x.EmailAddress = s.SubscriberKey 
    where e.clientid = 100 
+0

的可能的复制[如何创建内部CURSOR动态SQL查询(http://stackoverflow.com/questions/16394720/how -to-create-dynamic-sql-queries-cursor-cursor) –

+0

我是seconding @Juan。你想要的东西好像是一个动态的sql来填充一个sql命令数组,然后执行它。 –

回答

0

你有几张桌子?如果没有太多的一个选项是左连接所有这些

left join c100.table1 x1 on x1.EmailAddress = s.SubscriberKey and [e.name] = 'table1' 
left join c100.table2 x1 on x2.EmailAddress = s.SubscriberKey and [e.name] = 'table2' 
etc... 

,然后在选择

coalesce(x1.HL_ACCT_ID, x2.HL_ACCT_ID, etc...) as 'HL_ACCT_ID', 
1

也许你可以只创建一个输出的所有e.name表的union一个看法?然后加入视图。

为了保持这一点,假设您只有两个不同的表,其名称可能在e.name列中,SubscriberEmail1SubscriberEmail2

然后,你可以创建这样一个观点:

CREATE VIEW SubscriberEmailUnion 
AS 
    SELECT 
     'SubscriberEmail1' as TableName, 
     HL_ACCT_ID, 
     SALE_CODE, 
     EmailAddress 
    FROM SubscriberEmail1 

    UNION 

    SELECT 
     'SubscriberEmail2' as TableName, 
     HL_ACCT_ID, 
     SALE_CODE, 
     EmailAddress 
    FROM SubscriberEmail2 
GO 

注意的是,鉴于各部分是增加的名字是基础表的列。然后,您可以更改您的最终加入到:

inner join SubscriberEmailUnion x with (nolock) on (
    x.EmailAddress = s.SubscriberKey 
    AND x.TableName = e.Name 
) 

我个人最熟悉MS Sql Server所以我的示例使用语法。如果有必要,应该很容易改变以使用不同的服务器。

出于性能,那么你可以使用任何功能,您的数据库有,索引视图等