user2857662
user2857662

Reputation: 1

select entries of different columns of different tables using dynamic query

I have two tables

studentTable

Id | Studentname | Adress

teacherTable

TID | TeacherName | Adress

In studentTable table I have columns Id and in teacherTable I have a column TID, while using dynamic query how do I select the entries regardless of column name.

select ID or PID from @Tablename 

does not work, how can I do it, any idea?

The query which I tried:

SELECT  + '''' +  @TABLE_NAME + '''' + ',' + '''' +  @COLUMN_NAME + '''' + ',' + 'ID  + 
        ' FROM [' + @TABLE_NAME       

Upvotes: 0

Views: 188

Answers (1)

Hogan
Hogan

Reputation: 70528

You don't need a dynamic query, that would be slow.

Here is how you do it, two queries unioned together.

SELECT 'student' as [type], ID as [ID], studentname as name, address
from studentTable
where ID = @inID

union all

SELECT 'teacher' as [type], TID as [ID], teachername as name, address
from teacherTable
where TID = @inID

Upvotes: 1

Related Questions