如何查询sql server数据库大小 [英] how to query sql server database size
问题描述
在编写 C# 代码时,如果我能设法获得一个 SqlConnection,有没有办法执行查询来获取数据库的大小?
When writing C# code, if I can manage to get a SqlConnection, is there any way to perform a query to get the size of the Database?
上网查了一下,好像可以用"sp_spaceused",但它不是一张表,而是一个过程.
I searched the internet, seems "sp_spaceused" can be used, but it is not a table, it is a procedure.
我可以查询程序吗?
推荐答案
以下代码(取自控制台应用程序 testharness)使用 ADO.NET 调用 sp_spaceused 过程,然后迭代生成的 datareader 以获取数据库大小.
The following code (taken from a console app testharness) calls the sp_spaceused procedure using ADO.NET and then iterates the resulting datareader to get the db size.
这有效,但我不能说没有更有效或更直接的方法来实现您想要的.
This works, but I can't say that there isn't a more efficient or direct way of achieving what you want.
另一种实现方式是将 sp_spaceused 过程包装在您自己的过程中,以提供您需要的确切数据作为标量返回值.
One alternative implementation would be to wrap the sp_spaceused procedure in your own procedure that gives the exact data your need as a scalar return value.
class Program
{
static void Main(string[] args)
{
string strCount;
SqlConnection Conn = new SqlConnection
("Data Source=ServerName;integrated " +
"Security=sspi;initial catalog=TestingDB;");
SqlCommand testCMD = new SqlCommand
("sp_spaceused", Conn);
testCMD.CommandType = CommandType.StoredProcedure;
Conn.Open();
SqlDataReader reader = testCMD.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("Name: " + reader["database_name"]);
Console.WriteLine("Size: " + reader["database_size"]);
}
}
Console.ReadLine();
}
}
这篇关于如何查询sql server数据库大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!