如果表为空,则选择表的名称

时间:2016-08-04 15:18:29

标签: sql sql-server cursor subquery

我有桌子名称的表......

我只需要选择那些空的表。

为此我试过写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

这就是我所拥有的,但我无法编写正确的查询来选择空表的名称

我收到错误

  

Msg 105,Level 15,State 1,Line 1
  字符串'_test12345678910111213141'后的未闭合引号。

     

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

1 个答案:

答案 0 :(得分: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