为我们的网络创建数据库目录

时间:2014-07-29 17:10:35

标签: sql sql-server

该项目的最终产品是为我们所有的服务器创建数据库目录。它需要是动态的,因此当我们更改服务器的名称和位置时,我们仍然可以报告它们。通常,我们希望创建一个包含服务器名称,数据库名称,表名称和列名称的表。从那里我将使用报表设计器以高管的方式显示结果。

我的想法是使用Excel工作表作为服务器名称列表。从那里我应该能够查询所有其他信息。在下面的代码中,我将手动填充服务器名称。

现在我的代码将获取第一行信息:第一个服务器名称,第一个数据库名称,第一个表名称,第一列名称。我需要做的是为第一个表中的每个列名创建一行,然后转到下一个表,直到该数据库中的所有表都完成,然后移到下一个数据库,直到所有数据库都是完成,然后转到下一个服务器。我想我有所有基本的部分,但需要帮助子查询。

--- Drop and recreate the Servers_To_Catalog table if it exists.
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Servers_To_Catalog]') AND TYPE IN (N'U'))
DROP TABLE [dbo].[Servers_To_Catalog]
go

CREATE TABLE dbo.Servers_To_Catalog (ServerName nvarchar(50), Comment nvarchar(200));
GO

--------------------------------------------------------------------------------------------------------------------

--- Populate the Servers_To_Catalog table from an Excel sheet or manually below
Insert Into Servers_To_Catalog (ServerName) values ('CESDBS_OLD')
Insert Into Servers_To_Catalog (ServerName) values ('CESDBS')
Insert Into Servers_To_Catalog (ServerName) values ('DBS2000')
Insert Into Servers_To_Catalog (ServerName) values ('CESOES')
Insert Into Servers_To_Catalog (ServerName) values ('CESROUTE')
Insert Into Servers_To_Catalog (ServerName) values ('CESBS')
Insert Into Servers_To_Catalog (ServerName) values ('WHDBS')
Insert Into Servers_To_Catalog (ServerName) values ('CESDATA')

----------------------------------------------------------------------------------------------------------------------

--- Drop and recreate the temporary Database_Locations table if it exists.
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Database_Locations]') AND TYPE IN (N'U'))
DROP TABLE [dbo].[Database_Locations]
go

CREATE TABLE dbo.Database_Locations (ServerName nvarchar(50), DBName nvarchar(50), TableName nvarchar(50), ColumnName nvarchar(50));
GO

----------------------------------------------------------------------------------------------------------------------

--- Bring in the server names from the Servers_To_Catalog table as @SName.
DECLARE @SName NVARCHAR(50)
SELECT @SName = ServerName
From dbo.Servers_To_Catalog


--- Bring in the names of the databases on a given server as @DName, excluding system databases.
DECLARE @DName NVARCHAR (50)
SELECT @DName = NAME
From sys.databases
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')

--- Bring in the names of the tables for a given database as @TName
DECLARE @TName NVARCHAR(50) 
SELECT @TName = NAME
FROM sys.Tables


--- Use @TName to get the list of columns
Declare @CName NVarchar(50)
SELECT @CNAME = NAME
From syscolumns
Where id = object_id(@TName)

---Write row to Database_Locations table
Insert into dev.dbo.Database_Locations (ServerName, DBName, TableName, ColumnName)  Select @SName, @DName, @TName, @CName 

0 个答案:

没有答案