SQL query SELECT FROM [value from column of another table]

☆樱花仙子☆ 提交于 2019-12-01 11:20:38

Executing

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

Will output a series of sql statements like

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

that you can then execute "sql to build sql" if you will.

No, that is not possible. You can't use values as table names directly in a query, and you can't join each record against a different table.

You would have to make the join for a single record, and create the query dynamically to use a value as table name:

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')

With dynamic query:

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!