Sql-server – Create a View from Multiple Databases

sql servert-sql

Database X - tableCust - Column-CustNumber
Database Y - tableCust - Column-Custnumber
Datbase Z - tableCust - Column-Custnumber

I'm trying to create a view in database H from those three databases like below.

Select Custnumber,Orginal_DB_Name() as DatabaseName
from X.dbo.tablecust
Union 
Select Custnumber,Orginal_DB_Name() as DatabaseName
from Y.dbo.tablecust
;
;
;
etc

But the database name is showing me Master instead of their DB_Name.

It needs to show output like below:

Database_Name CustNumber
X               221
X               1223
Y                122
Y               233
"
"

Best Answer

Specify each database name explicitly as a string:

SELECT
  Custnumber,
  'X' AS DatabaseName
FROM
  X.dbo.tablecust

UNION

SELECT
  Custnumber,
  'Y' AS DatabaseName
FROM
  Y.dbo.tablecust

UNION

...

There is no other way. After all, you have to explicitly specify the database name in the table references too (X.dbo.tablecust, Y.dbo.tablecust etc.).