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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top