从许多基地

时间:2018-02-09 15:07:02

标签: c# sql tsql

如何从一个结果中的多个基础中的表中选择信息。我的想法是将它们放在DataTable中并在DataGrid中显示它们。

这是查询:

exec sp_msforeachdb 'use ?; IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb'' AND ''?'' <> ''addresses'' AND ''?'' <> ''ikamebeldizain'' AND ''?'' <> ''new2'' AND ''?'' <> ''sample'' AND ''?'' <> ''sitedatabase'' AND ''?'' <> ''StudentsTeachersTest'' AND ''?'' <> ''MicroinvestDatabasesCatalog'' select * from dbo.system;'

当我在dataGrid中尝试使用此查询时,我只有一行(第一个结果)。

2 个答案:

答案 0 :(得分:2)

要在SQL中附加多个结果集,您需要具有相同的结果结构(即:以相同的顺序返回相同的列)并告诉SQL将它们与union all一起使用(仅使用{ {1}}将删除重复的行)。要在不同的数据库中执行此操作,假设它们位于同一服务器上,您只需在查询中引用该数据库:

union

如果您尝试在动态数据库集中执行此操作,则只能使用动态SQL执行此操作,动态SQL将根据脚本中先前提供的数据库列表输出上述语句,您可以然后执行。

答案 1 :(得分:1)

我提出了一个解决方案:

    DECLARE @db_id AS int 
    DECLARE @db_name AS sysname
 CREATE TABLE ##CompatibleDatabases
    (       
      Name sysname, 
      CompanyName nvarchar(255),
      ProductID smallint,
      [Version] nvarchar(20),
      [Code] int
    )

    SET ROWCOUNT 0
    SELECT  dbid AS [ID], Name AS [Name] INTO #AllDatabases FROM master..sysdatabases
        SET ROWCOUNT 1
    SELECT @db_id = [ID] FROM #AllDatabases
        WHILE @@rowcount <> 0
    BEGIN

        SET ROWCOUNT 0

        BEGIN TRY

            SET @db_name = db_name(@db_id)

            EXEC ('IF (
                EXISTS ( SELECT * FROM [' + @db_name + '].INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=''System'') AND
                EXISTS ( SELECT * FROM [' + @db_name + '].INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=''System'' AND COLUMN_NAME=''ProductID'' ) AND
                EXISTS ( SELECT * FROM [' + @db_name + '].INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=''System'' AND COLUMN_NAME=''Version'' ) 
            )
            BEGIN
                DECLARE @insertStatement nvarchar(500)

                IF (EXISTS ( SELECT * FROM [' + @db_name + '].INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=''System'' AND COLUMN_NAME=''CompanyName'' ) )
                    SET @insertStatement=''INSERT INTO ##CompatibleDatabases SELECT ''''' + @db_name + ''''' AS Name, CompanyName, ProductID, [Version], [Code] FROM [' + @db_name + '].dbo.System''
                ELSE
                    SET @insertStatement=''INSERT INTO ##CompatibleDatabases SELECT ''''' + @db_name + ''''' AS Name,''''' + @db_name + ''''' AS CompanyName, ProductID, [Version], NULL AS Code FROM [' + @db_name + '].dbo.System''

                EXEC(@insertStatement) 
            END')

        END TRY

        BEGIN CATCH

        END CATCH

        DELETE #AllDatabases WHERE [ID] = @db_id

        SET ROWCOUNT 1
        SELECT @db_id = [ID] FROM #AllDatabases 
    END

    SET ROWCOUNT 0
    select * from ##CompatibleDatabases

    DROP TABLE #AllDatabases
    DROP TABLE ##CompatibleDatabases