Sql查询数据库中表的使用空间以及表结构
一 . Sql server 查询数据库中表的使用空间及表结构
1.查询单表
点击查看代码
EXEC sp_spaceused 'dbo.tablename'
2.查询所有表
点击查看代码
SELECT t.NAME AS TableName, -- 表明s.Name AS SchemaName, -- 架构名
p.rows AS RowCounts, -- 总行数
SUM(a.total_pages) * 8 AS TotalSpaceKB, --总空间kb
CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB, --使用空间
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB, -- 未使用空间
CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME NOT LIKE 'dt%' -- 表名
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255 AND p.rows>80000 -- 表的总条数大于80000
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
t.Name
3.查询表结构
点击查看代码
SELECT CASE WHEN col.colorder = 1 THEN obj.name
ELSE ''
END AS 表名,
col.colorder AS 序号 ,
col.name AS 列名 ,
ISNULL(ep.[value], '') AS 列说明 ,
t.name AS 数据类型 ,
col.length AS 长度 ,
ISNULL(COLUMNPROPERTY(col.id, col.name, 'Scale'), 0) AS 小数位数 ,
CASE WHEN COLUMNPROPERTY(col.id, col.name, 'IsIdentity') = 1 THEN '√'
ELSE ''
END AS 标识 ,
CASE WHEN EXISTS ( SELECT 1
FROM dbo.sysindexes si
INNER JOIN dbo.sysindexkeys sik ON si.id = sik.id
AND si.indid = sik.indid
INNER JOIN dbo.syscolumns sc ON sc.id = sik.id
AND sc.colid = sik.colid
INNER JOIN dbo.sysobjects so ON so.name = si.name
AND so.xtype = 'PK'
WHERE sc.id = col.id
AND sc.colid = col.colid ) THEN '√'
ELSE ''
END AS 主键 ,
CASE WHEN col.isnullable = 1 THEN '√'
ELSE ''
END AS 允许空 ,
ISNULL(comm.text, '') AS 默认值
FROM dbo.syscolumns col
LEFT JOIN dbo.systypes t ON col.xtype = t.xusertype
inner JOIN dbo.sysobjects obj ON col.id = obj.id
AND obj.xtype = 'U'
AND obj.status >= 0
LEFT JOIN dbo.syscomments comm ON col.cdefault = comm.id
LEFT JOIN sys.extended_properties ep ON col.id = ep.major_id
AND col.colid = ep.minor_id
AND ep.name = 'MS_Description'
LEFT JOIN sys.extended_properties epTwo ON obj.id = epTwo.major_id
AND epTwo.minor_id = 0
AND epTwo.name = 'MS_Description'
WHERE obj.name = 'T_Contract'--数据库表名
ORDER BY col.colorder ;
二.MySql查询数据库中表的使用空间及表结构
1.查询表结构
点击查看代码
SELECT
COLUMN_NAME 列名,
COLUMN_TYPE 数据类型,
DATA_TYPE 字段类型,
CHARACTER_MAXIMUM_LENGTH 长度,
case WHEN IS_NULLABLE='YES' THEN '√' ELSE '' END 是否为空,
COLUMN_DEFAULT 默认值,
COLUMN_COMMENT 列说明
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE table_schema='aaa' -- 数据库名
and table_name = 'bbb' -- 表名
2.查询表所有表
点击查看代码
select * from information_schema.tables where table_schema='jepaas' --数据库名
无穷的伟大,也是从“0”开始的