选择SQL Server数据库大小

bxfogqkk  于 2022-09-18  发布在  Java
关注(0)|答案(12)|浏览(172)

如何查询我的SQL服务器以仅获得数据库的大小?

我用了这个:

use "MY_DB"
exec sp_spaceused

我得到了这个:

database_name   database_size   unallocated space
My_DB           17899.13 MB 5309.39 MB

它返回了几个我不需要的列,也许有从该存储过程中选择DATABASE_SIZE列的诀窍?

我还尝试了这个代码:

SELECT DB_NAME(database_id) AS DatabaseName,
       Name AS Logical_Name,
       Physical_Name,
       (size * 8) / 1024 SizeMB
FROM sys.master_files
WHERE DB_NAME(database_id) = 'MY_DB'

它给了我这样的结果:

DatabaseName    Logical_Name    Physical_Name                    SizeMB
MY_DB           MY_DB           D:MSSQLDataMY_DB.mdf          10613
MY_DB           MY_DB_log       D:MSSQLDataMY_DB.ldf          7286

所以我写了这样的话:

SELECT SUM(SizeMB)
FROM (
    SELECT DB_NAME(database_id) AS DatabaseName,
           Name AS Logical_Name,
           Physical_Name,
           (size * 8) / 1024 SizeMB
    FROM sys.master_files
    WHERE DB_NAME(database_id) = 'MY_DB'
) AS TEMP

我得到:1183

所以它是有效的,但也许有一种适当的方法来获得它?

smdncfj3

smdncfj31#

试试这件吧-

查询:

SELECT 
      database_name = DB_NAME(database_id)
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = 'LOG' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = 'ROWS' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))
FROM sys.master_files WITH(NOWAIT)
WHERE database_id = DB_ID() -- for current db 
GROUP BY database_id

输出:

-- my query
name           log_size_mb  row_size_mb   total_size_mb
-------------- ------------ ------------- -------------
xxxxxxxxxxx    512.00       302.81        814.81

-- sp_spaceused
database_name    database_size      unallocated space
---------------- ------------------ ------------------
xxxxxxxxxxx      814.81 MB          13.04 MB

功能:

ALTER FUNCTION [dbo].[GetDBSize] 
(
    @db_name NVARCHAR(100)
)
RETURNS TABLE
AS
RETURN

  SELECT 
        database_name = DB_NAME(database_id)
      , log_size_mb = CAST(SUM(CASE WHEN type_desc = 'LOG' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
      , row_size_mb = CAST(SUM(CASE WHEN type_desc = 'ROWS' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
      , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))
  FROM sys.master_files WITH(NOWAIT)
  WHERE database_id = DB_ID(@db_name)
      OR @db_name IS NULL
  GROUP BY database_id

更新2016/01/22:

显示有关大小、可用空间、上次数据库备份的信息

IF OBJECT_ID('tempdb.dbo.#space') IS NOT NULL
    DROP TABLE #space

CREATE TABLE #space (
      database_id INT PRIMARY KEY
    , data_used_size DECIMAL(18,2)
    , log_used_size DECIMAL(18,2)
)

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = STUFF((
    SELECT '
    USE [' + d.name + ']
    INSERT INTO #space (database_id, data_used_size, log_used_size)
    SELECT
          DB_ID()
        , SUM(CASE WHEN [type] = 0 THEN space_used END)
        , SUM(CASE WHEN [type] = 1 THEN space_used END)
    FROM (
        SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8. / 1024)
        FROM sys.database_files s
        GROUP BY s.[type]
    ) t;'
    FROM sys.databases d
    WHERE d.[state] = 0
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

EXEC sys.sp_executesql @SQL

SELECT
      d.database_id
    , d.name
    , d.state_desc
    , d.recovery_model_desc
    , t.total_size
    , t.data_size
    , s.data_used_size
    , t.log_size
    , s.log_used_size
    , bu.full_last_date
    , bu.full_size
    , bu.log_last_date
    , bu.log_size
FROM (
    SELECT
          database_id
        , log_size = CAST(SUM(CASE WHEN [type] = 1 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , data_size = CAST(SUM(CASE WHEN [type] = 0 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , total_size = CAST(SUM(size) * 8. / 1024 AS DECIMAL(18,2))
    FROM sys.master_files
    GROUP BY database_id
) t
JOIN sys.databases d ON d.database_id = t.database_id
LEFT JOIN #space s ON d.database_id = s.database_id
LEFT JOIN (
    SELECT
          database_name
        , full_last_date = MAX(CASE WHEN [type] = 'D' THEN backup_finish_date END)
        , full_size = MAX(CASE WHEN [type] = 'D' THEN backup_size END)
        , log_last_date = MAX(CASE WHEN [type] = 'L' THEN backup_finish_date END)
        , log_size = MAX(CASE WHEN [type] = 'L' THEN backup_size END)
    FROM (
        SELECT
              s.database_name
            , s.[type]
            , s.backup_finish_date
            , backup_size =
                        CAST(CASE WHEN s.backup_size = s.compressed_backup_size
                                    THEN s.backup_size
                                    ELSE s.compressed_backup_size
                        END / 1048576.0 AS DECIMAL(18,2))
            , RowNum = ROW_NUMBER() OVER (PARTITION BY s.database_name, s.[type] ORDER BY s.backup_finish_date DESC)
        FROM msdb.dbo.backupset s
        WHERE s.[type] IN ('D', 'L')
    ) f
    WHERE f.RowNum = 1
    GROUP BY f.database_name
) bu ON d.name = bu.database_name
ORDER BY t.total_size DESC

输出:

database_id name                             state_desc   recovery_model_desc total_size   data_size   data_used_size  log_size    log_used_size  full_last_date          full_size    log_last_date           log_size
----------- -------------------------------- ------------ ------------------- ------------ ----------- --------------- ----------- -------------- ----------------------- ------------ ----------------------- ---------
24          StackOverflow                    ONLINE       SIMPLE              66339.88     65840.00    65102.06        499.88      5.05           NULL                    NULL         NULL                    NULL
11          AdventureWorks2012               ONLINE       SIMPLE              16404.13     15213.00    192.69          1191.13     15.55          2015-11-10 10:51:02.000 44.59        NULL                    NULL
10          locateme                         ONLINE       SIMPLE              1050.13      591.00      2.94            459.13      6.91           2015-11-06 15:08:34.000 17.25        NULL                    NULL
8           CL_Documents                     ONLINE       FULL                793.13       334.00      333.69          459.13      12.95          2015-11-06 15:08:31.000 309.22       2015-11-06 13:15:39.000 0.01
1           master                           ONLINE       SIMPLE              554.00       492.06      4.31            61.94       5.20           2015-11-06 15:08:12.000 0.65         NULL                    NULL
9           Refactoring                      ONLINE       SIMPLE              494.32       366.44      308.88          127.88      34.96          2016-01-05 18:59:10.000 37.53        NULL                    NULL
3           model                            ONLINE       SIMPLE              349.06       4.06        2.56            345.00      0.97           2015-11-06 15:08:12.000 0.45         NULL                    NULL
13          sql-format.com                   ONLINE       SIMPLE              216.81       181.38      149.00          35.44       3.06           2015-11-06 15:08:39.000 23.64        NULL                    NULL
23          users                            ONLINE       FULL                173.25       73.25       3.25            100.00      5.66           2015-11-23 13:15:45.000 0.72         NULL                    NULL
4           msdb                             ONLINE       SIMPLE              46.44        20.25       19.31           26.19       4.09           2015-11-06 15:08:12.000 2.96         NULL                    NULL
21          SSISDB                           ONLINE       FULL                45.06        40.00       4.06            5.06        4.84           2014-05-14 18:27:11.000 3.08         NULL                    NULL
27          tSQLt                            ONLINE       SIMPLE              9.00         5.00        3.06            4.00        0.75           NULL                    NULL         NULL                    NULL
2           tempdb                           ONLINE       SIMPLE              8.50         8.00        4.50            0.50        1.78           NULL                    NULL         NULL                    NULL
wlwcrazw

wlwcrazw2#

还将结果与以下查询的结果进行比较

EXEC sp_helpdb @dbname= 'MSDB'

它会产生类似以下结果的结果

有一篇好文章--Different ways to determine free space for SQL Server databases and database files

3gtaxfhh

3gtaxfhh3#

非常适合我在SQL Server 2012中计算SQL数据库大小

exec sp_spaceused
lsmd5eda

lsmd5eda4#

这里已经有很多很好的答案,但值得一提的是,使用标准报告通过SQL Server Management Studio(SSMS)获得SQL Server数据库大小的一种简单快速的方法。

要运行报表,您需要:

1.右击数据库
1.转到报告>标准报告>磁盘使用。

它打印出一份漂亮的报告:

其中保留的总空间是磁盘上数据库的总大小,它包括所有数据文件的大小和所有事务日志文件的大小。

在幕后,SSMS使用dbo.sysfiles视图或sys.database_files视图(取决于MSSQL的版本)和某种类型的查询来获取总空间预留值:

SELECT sum((convert(dec (19, 2),  
convert(bigint,SIZE))) * 8192 / 1048576.0) db_size_mb
FROM dbo.sysfiles;
x6h2sr28

x6h2sr285#

  • 检查Azure和内部部署的SQL Server中的数据库大小-*

方法1-使用‘sys.database_files’系统视图

SELECT
    DB_NAME() AS [database_name],
    CONCAT(CAST(SUM(
        CAST( (size * 8.0/1024) AS DECIMAL(15,2) )
    ) AS VARCHAR(20)),' MB') AS [database_size]
FROM sys.database_files;

方法2-使用‘sp_spaceused’系统存储过程

EXEC sp_spaceused ;
m2xkgtsf

m2xkgtsf6#

SELECT      sys.databases.name AS [Database Name],  
        CONVERT(VARCHAR,SUM(size)*8/1024)+' MB' AS [Size]  
     FROM        sys.databases   
     JOIN        sys.master_files  
     ON          sys.databases.database_id=sys.master_files.database_id  
     GROUP BY    sys.databases.name  
     ORDER BY    sys.databases.name
i7uq4tfw

i7uq4tfw7#

EXEC sp_spaceused @oneresultset = 1在一行中显示所有结果

如果只执行‘exec sp_spaceused’,您将看到在SQL Server Management Studio v17.9中有两行工作

5lwkijsr

5lwkijsr8#

如果您想简单地检查单个数据库的大小,可以使用SSMS gui来完成。

进入服务器资源管理器->展开它->右击数据库->选择属性->在弹出窗口中选择常规选项卡->查看大小

来源:Check database size in Sql server ( Various Ways explained)

xkftehaa

xkftehaa9#

您可以在this link之后检查该查询的工作方式。

IF OBJECT_ID('tempdb..#spacetable') IS NOT NULL 
DROP TABLE tempdb..#spacetable 
create table #spacetable
(
database_name varchar(50) ,
total_size_data int,
space_util_data int,
space_data_left int,
percent_fill_data float,
total_size_data_log int,
space_util_log int,
space_log_left int,
percent_fill_log char(50),
[total db size] int,
[total size used] int,
[total size left] int
)
insert into  #spacetable
EXECUTE master.sys.sp_MSforeachdb 'USE [?];
select x.[DATABASE NAME],x.[total size data],x.[space util],x.[total size data]-x.[space util] [space left data],
x.[percent fill],y.[total size log],y.[space util],
y.[total size log]-y.[space util] [space left log],y.[percent fill],
y.[total size log]+x.[total size data] ''total db size''
,x.[space util]+y.[space util] ''total size used'',
(y.[total size log]+x.[total size data])-(y.[space util]+x.[space util]) ''total size left''
 from (select DB_NAME() ''DATABASE NAME'',
sum(size*8/1024) ''total size data'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
,case when sum(size*8/1024)=0 then ''divide by zero'' else
substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
from sys.master_files where database_id=DB_ID(DB_NAME())  and  type=0
group by type_desc  ) as x ,
(select 
sum(size*8/1024) ''total size log'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
,case when sum(size*8/1024)=0 then ''divide by zero'' else
substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
from sys.master_files where database_id=DB_ID(DB_NAME())  and  type=1
group by type_desc  )y'
select * from #spacetable 
order by database_name
drop table #spacetable
ddhy6vgd

ddhy6vgd10#

SELECT
    DB_NAME (database_id) as [Database Name],
    name as [Database File Name],
    [Type] = CASE WHEN Type_Desc = 'ROWS' THEN 'Data File(s)'
            WHEN Type_Desc = 'LOG'  THEN 'Log File(s)'
            ELSE Type_Desc END,
    size*8/1024 as 'Size (MB)',
    physical_name as [Database_File_Location]
FROM sys.master_files
ORDER BY 1,3

输出

Database Name               Database File Name              Type                Size (MB)   Database_File_Location
--------------------------- ------------------------------- ------------------- ----------- ---------------------------------------------------------------
AdventureWorksDW2017        AdventureWorksDW2017            Data File(s)        136         E:MSSQL14.MSSQLSERVERMSSQLDATAAdventureWorksDW2017.mdf
AdventureWorksDW2017        AdventureWorksDW2017_log        Log File(s)         72          E:MSSQL14.MSSQLSERVERMSSQLDATAAdventureWorksDW2017_log.ldf
DBA_Admin                   DBA_Admin                       Data File(s)        8           E:MSSQL14.MSSQLSERVERMSSQLDATADBA_Admin.mdf
DBA_Admin                   DBA_Admin_log                   Log File(s)         8           E:MSSQL14.MSSQLSERVERMSSQLDATADBA_Admin_log.ldf
EventNotifications          EventNotifications              Data File(s)        8           E:MSSQL14.MSSQLSERVERMSSQLDATAEventNotifications.mdf
EventNotifications          EventNotifications_log          Log File(s)         8           E:MSSQL14.MSSQLSERVERMSSQLDATAEventNotifications_log.ldf
master                      master                          Data File(s)        4           E:MSSQL14.MSSQLSERVERMSSQLDATAmaster.mdf
master                      mastlog                         Log File(s)         2           E:MSSQL14.MSSQLSERVERMSSQLDATAmastlog.ldf
model                       modeldev                        Data File(s)        8           E:MSSQL14.MSSQLSERVERMSSQLDATAmodel.mdf
model                       modellog                        Log File(s)         8           E:MSSQL14.MSSQLSERVERMSSQLDATAmodellog.ldf
msdb                        MSDBData                        Data File(s)        19          E:MSSQL14.MSSQLSERVERMSSQLDATAMSDBData.mdf
msdb                        MSDBLog                         Log File(s)         13          E:MSSQL14.MSSQLSERVERMSSQLDATAMSDBLog.ldf
tempdb                      temp2                           Data File(s)        8           E:MSSQL14.MSSQLSERVERMSSQLDATAtempdb_mssql_2.ndf
tempdb                      temp3                           Data File(s)        8           E:MSSQL14.MSSQLSERVERMSSQLDATAtempdb_mssql_3.ndf
tempdb                      temp4                           Data File(s)        8           E:MSSQL14.MSSQLSERVERMSSQLDATAtempdb_mssql_4.ndf
tempdb                      tempdev                         Data File(s)        8           E:MSSQL14.MSSQLSERVERMSSQLDATAtempdb.mdf
tempdb                      templog                         Log File(s)         8           E:MSSQL14.MSSQLSERVERMSSQLDATAtemplog.ldf
ar7v8xwq

ar7v8xwq11#

试试下面的代码。它的代码非常好:

with CteDbSizes
as
(
    select database_id, type, size * 8.0 / 1024 size
    from sys.master_files
)
select 
    dbFileSizes.[name] AS DatabaseName,
    (select sum(size) from CteDbSizes where type = 1 and CteDbSizes.database_id = dbFileSizes.database_id) LogFileSizeMB,
    (select sum(size) from CteDbSizes where type = 0 and CteDbSizes.database_id = dbFileSizes.database_id) DataFileSizeMB
from sys.databases dbFileSizes ORDER BY DataFileSizeMB desc
niwlg2el

niwlg2el12#

如果你想获得真实数据的大小,你只需要过滤‘在线’数据文件。否则,您可能会得到一个与您在图形用户界面中看到的大小显著不同的大小。一些Ghost|旧垃圾记录可能在sys.master_files中,例如‘Deunct’数据文件。

with fs
    as
    (
        select database_id, type, size * 8.0 / 1024 size, physical_name
        from sys.master_files
        where state_desc = 'ONLINE' -- ONLINE,RESTORING,RECOVERING,RECOVERY_PENDING,SUSPECT,,OFFLINE, DEFUNCT
    )
    select 
        name,
        (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,
        (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB,
        (select sum(size) from fs where fs.database_id = db.database_id) TotalFileSizeMB
    from sys.databases db
    --order by database_id
    order by TotalFileSizeMB desc

相关问题