2017-08-17 99 views
-4

我在我的數據庫中有4個表。我想編寫一個返回表名的單個查詢,不。的行,表大小,日期表被創建和修改,誰創建的表是由。加入SQL服務器查詢

我的數據庫:

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'); 
+0

你有什麼已經嘗試過? –

+0

首先查看'[master] .sys.tables'表 – dbajtr

回答

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

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.