开发者

Returning table type in table union in SQL

I have union of two tables, these tables don't have column type, but I need to return table name (or similar identification) 开发者_如何学编程so I can know in my code which table it was from. I'm using Microsoft SQL Server 2008 R2.

Here is my current SQL, that doesn't return type yet.

select Id, Name, CHAR(0) as Type 
  from Table1 
union all 
select Id, Name, CHAR(1) as Type 
  from Table2;


The solution:

select Id, Name, 'Table_1' as Type from Table1 
union all 
select Id, Name, 'Table_2' as Type from Table2;


How about this:

select 'Table1' as Type, Id, Name from Table1 
union all select 'Table2' as type, Id, Name from Table2;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜