使用动态查询选择不同表的不同列的条目

时间:2013-10-28 14:19:37

标签: sql sql-server stored-procedures

我有两张桌子

studentTable

Id | Studentname | Adress

teacherTable

TID | TeacherName | Adress

studentTable表中我有Id列,teacherTable我有一列TID,而使用动态查询时,如何选择条目而不管列名。

select ID or PID from @Tablename 

不起作用,我怎么能这样做,任何想法?

我试过的查询:

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

1 个答案:

答案 0 :(得分:1)

您不需要动态查询,这会很慢。

这是你如何做到的,两个查询联合在一起。

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