Domanda

Ho unione di due tabelle, queste tabelle non hanno un tipo di colonna, ma devo restituire il nome della tabella (o identificazione simile) in modo da poter sapere nel mio codice da quale tabella proveniva. Sto usando Microsoft SQL Server 2008 R2.

Ecco il mio SQL attuale, che non restituisce ancora.

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

Soluzione

La soluzione:

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

Altri suggerimenti

Cosa ne pensi di questo:

select 'Table1' as Type, Id, Name from Table1 
union all select 'Table2' as type, Id, Name from Table2;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top