2016-08-04 60 views
1

我有表名和表...如果表爲空,則選擇表的名稱

我只需要選擇那些空的表。

爲此,我試着寫CURSOR。

DECLARE @Footprint VARCHAR(200) 
DECLARE @query VARCHAR(200) 
DECLARE MY_CURSOR CURSOR 
    LOCAL STATIC READ_ONLY FORWARD_ONLY 
FOR 
SELECT '[' + [SchemaName] + '].[FootprintBuildState]' 
FROM [dbo].[vwAgencySchemas] 

OPEN MY_CURSOR 
FETCH NEXT FROM MY_CURSOR INTO @Footprint 
WHILE @@FETCH_STATUS = 0 
BEGIN 
    --CHECK IF Table IS EMPTY (UNCORRECT) 
    SET @query = 'SELECT ' + @Footprint + ' FROM ' + @Footprint + ' WHERE NOT EXISTS (SELECT * FROM ' + @Footprint+ ') ' 
    EXEC (@query) 
    FETCH NEXT FROM MY_CURSOR INTO @Footprint 
END 
CLOSE MY_CURSOR 
DEALLOCATE MY_CURSOR 

這是我,但我不能寫正確的查詢選擇空表的名稱

我得到錯誤

消息105,級別15,狀態1,行1
字符串'_test12345678910111213141'後面未加上引號。

Msg 102,Level 15,State 1,Line 1
'_test12345678910111213141'附近的語法不正確。

回答

2

甭想光標 - 你可以很容易地只是一個簡單的,單一的SELECT語句做到這一點 - 是這樣的:

SELECT 
    t.NAME AS TableName, 
    p.rows AS RowCounts 
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 
    dbo.YourNamesTable tbl ON t.Name = tbl.TableName 
WHERE 
    p.Rows = 0 
GROUP BY 
    t.Name, p.Rows 
ORDER BY 
    t.Name 
+0

@demo:** **爲什麼'HAVING?!?! '應該只應用於**使用SUM,COUNT,AVG等的聚合列 - 我的列沒有使用聚合,所以** no **,不需要'HAVING' ... –

相關問題