Mukyuu
Mukyuu

Reputation: 6759

Is it possible to use the subquery value as SELECT FIELD and FROM?

I have 3 tables: table_sample1, table_sample2 and table_name_to_go.

table_sample1: table_sample1

table_sample2 : table_sample2

table_name_to_go: table_name_to_go

Fiddle example: https://www.db-fiddle.com/f/iWm37Kis3kYVGb3Y4SvVZw/1

What I would like to do is select the data from table_name_to_go (example: SELECT * from table_name_to_go where id = 1)

and then use the selected value as the SELECT field and FROM more or less: SELECT column_to_select FROM (SELECT * from table_name_to_go where id = 1).table_name; but it's not working.

What I expect is to be able to get:

FIELD
-----
demo

from table_sample1. Since table_name_to_go had FIELD as column to select and table_sample1 as table name.

Which brings me to the current question: Is it possible to use the subquery value as SELECT FIELD and FROM?

Upvotes: 1

Views: 44

Answers (1)

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

Use Dynamic SQL

DECLARE @ColName varchar(128)    
DECLARE @TableName varchar(128)  
DECLARE @sql varchar(4000)    
SET @ColName ='Code';
SET @TableName ='Code'; 

SET @sql = 'SELECT ' + @ColName + 'FROM '+ @TableName

EXEC sp_executesql @sql
GO

Upvotes: 1

Related Questions