具有动态连接数的存储过程

问题描述 投票:0回答:1

我正在尝试建立一个存储过程,该存储过程接受动态数量的表并将它们连接起来。

SELECT a.Account
FROM Database.Accounts a
JOIN (SELECT Table_Name FROM Database.TableStrings WHERE Row = 1) b ON a.Account = b.Account
JOIN (SELECT Table_Name FROM Database.TableStrings WHERE Row = 2) c ON a.Account = c.Account
JOIN (SELECT Table_Name FROM Database.TableStrings WHERE Row = 3) d ON a.Account = d.Account
...
/*Where the number of joins is equal to COUNT(Table_Name) FROM Database.TableStrings*/

first = SELECT a.Account
        FROM Database.Accounts a
        JOIN (SELECT Table_Name FROM Database.TableStrings WHERE Row = 1) b ON a.Account = b.Account

second = SELECT a.Account
         FROM first a
         JOIN (SELECT Table_Name FROM Database.TableStrings WHERE Row = 2) b ON a.Account = b.Account
...

下面是Database.TableStrings表中条目的示例:

Table_Name (String):
------------------------
'Database.PhoneNumbers'
'Database.Emails'
'Database.BankAccounts'

即使有可能,我也很难想象如何在存储过程中执行此操作。

sql sql-server database stored-procedures dynamic-sql
1个回答
0
投票

您可能考虑使用递归查询(cte)来处理字符串连接。并运行sp_executesql执行生成的SQL字符串查询

declare @strSQL nvarchar(max), @strSQLjoin nvarchar(max)

set @strSQL = 'SELECT a.Account
    FROM Database.Accounts a ';

set @strSQLjoin = '';

with cte as (
    select 'Database.PhoneNumbers' as TableStrings
    union all select 'Database.Emails'
    union all select 'Database.BankAccounts'
),
cte2 as (
    select @strSQLjoin as strS 
    union all 
    select @strSQLjoin + ' JOIN (SELECT Table_Name FROM '+TableStrings+' WHERE Row = 1) b ON a.Account = b.Account'
    from cte
)select @strSQLjoin = coalesce(@strSQLjoin+strS+ ' ', strS) from cte2 where strS!= '' ;

set @strSQL=@strSQL + @strSQLjoin;
print @strSQL
exec sp_executesql @strSQL
© www.soinside.com 2019 - 2024. All rights reserved.