带连接的SQL Server查询

时间:2017-08-17 10:56:43

标签: sql-server database

我的数据库中有4个表。我想写一个返回表名的查询,没有。行,表大小,日期表的创建和修改,谁是由。创建的表。

我的数据库:

 CREATE TABLE Branch(
      Br_ID int IDENTITY(1,1) PRIMARY KEY,
      Name varchar(255),
      Desp varchar(255)
 );

 CREATE TABLE Region(
      R_ID int IDENTITY(1,1) PRIMARY KEY,
      Name varchar(255),
      Desp varchar(255)
 );

 CREATE TABLE Customer(
      Cust_ID int IDENTITY(1,1) PRIMARY KEY,
      Name varchar(255),
      Desp varchar(255)
 );

 CREATE TABLE Customer_Branch(
      Br_ID int FOREIGN KEY REFERENCES Branch(Br_ID) not null,
      Cust_ID int FOREIGN KEY REFERENCES Customer(Cust_ID) not null,
      PRIMARY KEY (Br_ID, Cust_ID)
 );

 INSERT INTO Branch (Name, Desp)
 VALUES ('xyz', 'headoffice');

2 个答案:

答案 0 :(得分:0)

此查询将起作用应与SQL Server 2005及更高版本一起使用。

您可以运行此查询并进一步检查输出,您可以根据需要进行修改。

SELECT 
    t.NAME AS TableName,
    i.name as indexName,
    p.[Rows],
    sum(a.total_pages) as TotalPages, 
    sum(a.used_pages) as UsedPages, 
    sum(a.data_pages) as DataPages,
    (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB, 
    (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB, 
    (sum(a.data_pages) * 8) / 1024 as DataSpaceMB
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
WHERE 
    t.NAME NOT LIKE 'dt%' AND
    i.OBJECT_ID > 255 AND   
    i.index_id <= 1
GROUP BY 
    t.NAME, i.object_id, i.index_id, i.name, p.[Rows]
ORDER BY 
    object_name(i.object_id) 

输出:

enter image description here

答案 1 :(得分:0)

此查询将起作用应与SQL Server 2005及更高版本一起使用。

    SELECT 
    t.NAME AS TableName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    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,
    t.create_date AS [CreatedDate],
    t.modify_date AS [ModifiedDate]
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 
GROUP BY 
    t.Name, s.Name, p.Rows,t.create_date,t.modify_date
ORDER BY 
    t.Name

Result for given query.