通过变量从多个表中选择UNION

时间:2014-01-03 07:42:48

标签: sql-server-2008 while-loop union

我有一个查询,可以使用连接从多个表中进行选择。我想通过循环从不同的数据库执行此查询。

我通过(简化查询)完成了这个:

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

我的问题是结果会生成2个单独的表(对于每个循环)。我想结合结果,但不知道如何。

有什么建议吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

你不能使用类似下面代码的东西,你附加所有sqls与union,最后只执行一次sql而不在循环中执行。我不是SQL Server的专家,但我使用其他RDBMS编写了许多其他类似的存储过程。所以请承担任何语法错误。

DECLARE @intCounter int
DECLARE @maxId 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)
DECLARE @strSql varchar(5000)
SET @maxId = (SELECT MAX(ID) FROM @tblBedrijven)

WHILE (@intCounter <= @maxId)
BEGIN

    SET @strTable = (SELECT DatabaseTable FROM @tblBedrijven
                WHERE ID = @intCounter)
    SET @strCompany = (SELECT CompanyName FROM @tblBedrijven
                WHERE ID = @intCounter)
    SET @strSql = @strSql + ('SELECT ''' + @strCompany + ''' as Company,
        AUS.[User],
        AUS.[E-mail]
    FROM' + @strTable)
    IF @intCounter < @maxId THEN
    BEGIN
        SET @strSql = @strSql + ' UNION '
    END
    SET @intCounter = @intCounter + 1       
END

EXEC(@strSql)