I have a query that selects from multiple tables using a join. I want to execute this query from different databases via a loop.
I have accomplished that via (simplified query):
DECLARE @intCounter int
SET @intCounter = 1
DECLARE @tblBedrijven TABLE (ID int identity(1,1),
CompanyName varchar(20),
DatabaseTable varchar(100))
INSERT INTO @tblBedrijven VALUES ('001-CureCare', '<TABLE/ DATABASE1> AUS'),
('002-Cleaning', '[global_nav5_prod].[dbo].<TABLE/ DATABASE2>] AUS')
DECLARE @strCompany varchar(20)
DECLARE @strTable varchar(100)
WHILE (@intCounter <= (SELECT MAX(ID) FROM @tblBedrijven))
BEGIN
SET @strTable = (SELECT DatabaseTable FROM @tblBedrijven
WHERE ID = @intCounter)
SET @strCompany = (SELECT CompanyName FROM @tblBedrijven
WHERE ID = @intCounter)
EXEC('SELECT ''' + @strCompany + ''' as Company,
AUS.[User],
AUS.[E-mail]
FROM' + @strTable)
SET @intCounter = @intCounter + 1
END
My problem is that the result generates 2 separate tables (for every loop). I want to union the results but have no clue how.
Any suggestions?
Thanks in advance.