SQL查询SELECT FROM [另一个表的列中的值]

时间:2011-04-14 18:28:55

标签: sql-server select inner-join dynamic-sql

我有一个表X,当某些表发生更改时,触发器将插入一行。我已将表名插入表X.

现在,我想select来自表格X的数据inner join与实际的表格本身。是否可以通过使用select表的列中的值作为内连接的表?

查询应该看起来像这样

SELECT X.a, Y.b, Y.c FROM X
INNER JOIN [X.TableName] AS Y ON Y.ID = X.ID

3 个答案:

答案 0 :(得分:3)

执行

select 'SELECT X.a, Y.b, Y.c FROM X
INNER JOIN [' + X.TableName + '] AS Y ON X.ID = Y.ID 
where x.primarykey =' + x.primarykey from x

将输出一系列sql语句,如

SELECT X.a, Y.b, Y.c FROM X
INNER JOIN [ customer ] AS Y ON X.ID = Y.ID
where x.primarykey = 1234

如果愿意的话,你可以执行“sql to build sql”。

答案 1 :(得分:1)

不,那是不可能的。您不能在查询中直接使用值作为表名,也不能将每个记录连接到不同的表。

您必须为单个记录进行连接,并动态创建查询以将值用作表名:

declare @name varchar(50)
set @name = select TableName from X where ID = 42
exec('select X.a, Y.b, Y.c from X innner join ' + @name + ' as Y on Y.DI = X.ID where X.ID = 42')

答案 2 :(得分:0)

使用动态查询:

DECLARE @table AS NVARCHAR(128);
DECLARE @sql NVARCHAR(4000);

-- of course you'll have to add your WHERE clause here 
SELECT @table = TableName FROM X;
SET @sql = 'SELECT X.a, Y.b, Y.c FROM X INNER JOIN '+@table+' AS Y ON Y.ID = X.ID';

EXEC(@sql);