如何以编程方式访问有关我的数据库的数据?

时间:2011-01-21 20:18:38

标签: c# .net sql-server-2005 .net-4.0

我想访问表的列表,并为每个表报告行数,使用的磁盘空间等。在数据库级别获取这些详细信息也很不错。

如何以编程方式执行此操作?

4 个答案:

答案 0 :(得分:2)

杰森上面的答案很好,但更普遍。你在看Information Schema。也是维基百科的条目:

http://en.wikipedia.org/wiki/Information_schema

答案 1 :(得分:1)

您只需打开一个连接并查询数据库:

using(var connection = new SqlConnection(connectionString)) {
    connection.Open();
    using(var command = connection.CreateCommand()) {
        command.CommandText = "SELECT * FROM SYS.TABLES";
        using(var reader = command.ExecuteReader()) {
            while(reader.Read()) {
                Console.WriteLine(reader["name"]);
            }
        }
    }
}

您可以在Google上查找所需其他信息的查询字符串。

答案 2 :(得分:0)

为您的数据库创建SqlConnection并打开连接。

SqlConnection conn = new SqlConnection("Data Source=Servername;Initial Catalog=Marketing;Integrated Security=SSPI");
conn.Open();

创建SqlCommand并将CommandText分配给您需要的SQL值。

SqlCommand cmd = new SqlCommand("PLACE SQL HERE", conn);

表格和行数:

SELECT 
    [TableName] = so.name, 
    [RowCount] = MAX(si.rows) 
FROM 
    sysobjects so, 
    sysindexes si 
WHERE 
    so.xtype = 'U' 
    AND 
    si.id = OBJECT_ID(so.name) 
GROUP BY 
    so.name 
ORDER BY 
    2 DESC

使用的空间:

EXEC sp_spaceused 'tablename'

答案 3 :(得分:0)

此脚本不包含架构名称,但可以获取当前数据库所需的大部分信息。我相信你可以将它改编成存储过程。

SET NOCOUNT ON
GO
DECLARE @tblSpaceUsed TABLE
(
    [name] sysname NOT NULL,
    [rows] int NOT NULL,
    [reserved] nvarchar(50) NOT NULL,
    [reservedKB] int NULL,
    [data] nvarchar(50) NOT NULL,
    [dataKB] int NULL,
    [index] nvarchar(50) NOT NULL,
    [indexKB] int NULL,
    [unused] nvarchar(50) NOT NULL,
    [unusedKB] int NULL
)

DECLARE @tableName sysname
DECLARE @tableNames CURSOR

SET @tableNames = CURSOR
FAST_FORWARD
FOR
SELECT DISTINCT
    ss.name + '.' + st.name
FROM 
    sys.tables st
    INNER JOIN
    sys.schemas ss
        ON st.schema_id = ss.schema_id

OPEN @tableNames 
FETCH NEXT FROM @tableNames INTO @tableName

WHILE @@FETCH_STATUS = 0
BEGIN
    INSERT INTO @tblSpaceUsed ([name], [rows], [reserved], [data], [index], [unused]) EXEC sp_spaceused @tableName

    FETCH NEXT FROM @tableNames INTO @tableName
END

CLOSE @tableNames

UPDATE 
    @tblSpaceUsed
SET
    [reservedKB] = CONVERT(int, LEFT([reserved], LEN([reserved]) - 3)),
    [dataKB] = CONVERT(int, LEFT([data], LEN([data]) - 3)),
    [indexKB] = CONVERT(int, LEFT([index], LEN([index]) - 3)),
    [unusedKB] = CONVERT(int, LEFT([unused], LEN([unused]) - 3))

SELECT
    *
FROM
    @tblSpaceUsed