views:

655

answers:

2

I am having separate database for each dept.I have all depts list in a master database table.All database are named as a1,a2 etc Now i want to fetch the employee detail from all the dept databses returned by a query.pls help me

+2  A: 

something like:

select <columnlist>, '[databasename1]' AS dbname 
  from [databasename1].[owner].[table or view name]
UNION
select <columnlist>, '[databasename2]' AS dbname  
  from [databasename2].[owner].[table or view name]
UNION 
select <columnlist>, '[databasename3]' AS dbname  
  from [databasename3].[owner].[table or view name]

Implementation:

DECLARE @DBTable TABLE (ID INT, DBName VARCHAR(20), DBOwner VARCHAR(10))
INSERT INTO @DBTable
SELECT 1, 'a1', 'dbo' UNION
SELECT 2, 'a2', 'dbo' UNION
SELECT 3, 'a3', 'dbo' UNION
SELECT 4, 'a5', 'dbo' 

DECLARE @Table VARCHAR(100), @Columns VARCHAR(500), @SQL VARCHAR(8000)
SELECT @Table = 'Emloyee', @Columns = 'ID, Name, Phone', @SQL = ''
SELECT @SQL = @SQL + '
SELECT '+@Columns+', '''+DBName+''' AS Database FROM ['+DBName+'].['+DBOwner+'].['+@Table+'] UNION'
FROM @DBTable
SET @SQL = SUBSTRING(@SQL, 0, LEN(@SQL) - 5)
EXEC(@SQL)
Max Gontar
+1  A: 

You can fetch tables across DBs like this:-

SELECT * FROM a1..Employee
UNION ALL
SELECT * FROM a2..Employee
AnthonyWJones

related questions