satck djallil
satck djallil

Reputation: 43

Select field from a table its name come from an other select

My second problem is simple to explain, but hard for me to resolve.

I want to Select values from table_Name when this table_Name comes from an other Select

Take this Example:

First Select

SELECT
    (SELECT ad_table.tablename
    FROM ad_table
    WHERE ad_table.ad_table_id =fact_acct.ad_table_id
    )
  FROM fact_acct

Result = C_Invoice

Second Select

 SELECT documentNo
    FROM
      (SELECT
        (SELECT ad_table.tablename
        FROM ad_table
        WHERE ad_table.ad_table_id =fact_acct.ad_table_id
        )
      FROM fact_acct
      ) 

This Select must be The same as: SELECT documentNo from C_Invoice

So any ideas?

Upvotes: 0

Views: 49

Answers (1)

Jaydip Jadhav
Jaydip Jadhav

Reputation: 12309

Using Dynamic SQL Query try like this

DECLARE @TableName NVARCHAR(MAX)
DECLARE @Sql NVARCHAR(MAX)

SELECT @TableName = ad_table.tablename
FROM ad_table
WHERE ad_table.ad_table_id =fact_acct.ad_table_id

SET @Sql='SELECT documentNo FROM '+@TableName

EXEC(@Sql)

Upvotes: 1

Related Questions