我们如何通过sys检查表中是否存在数据。表格/功能直接

时间:2013-12-18 09:37:36

标签: sql-server tsql database-schema

有没有办法通过sys检查表中是否存在数据。表或函数直接查询表。

任何此类系统。可用?

**不查询动态sql .. :))

2 个答案:

答案 0 :(得分:1)

阅读这篇文章:

Find Row Count in Table – Find Largest Table in Database

以下是查找表的ROWCOUNT的查询:

SELECT SUM(pa.rows) RowCnt
 FROM sys.tables ta
 INNER JOIN sys.partitions pa
 ON pa.OBJECT_ID = ta.OBJECT_ID

 WHERE ta.is_ms_shipped = 0 
       AND pa.index_id IN (1,0)
       AND ta.name='table1'

SQLFiddle demo

或者,如果您只需要有关空表的信息,那么就像这样:

SELECT 
ISNULL(
(SELECT TOP 1 1 from sys.partitions pa 
                       where pa.OBJECT_ID = ta.OBJECT_ID
                             AND
                             pa.rows>0
                             AND 
                             pa.index_id IN (1,0)                  
                 )
,0) as TableIsNotEmpty
 FROM sys.tables ta
 WHERE ta.is_ms_shipped = 0 
       AND ta.name='table1'

答案 1 :(得分:0)

-- This is how I got the result... 
SELECT  Distinct tbl.name, C.name  , X.rowcnt              
FROM        Sys.Columns          as     c
INNER JOIN  Sys.Tables           as     tbl
ON          tbl.object_id        =             c.object_id
INNER JOIN  Sys.Types            as     t
ON          c.system_type_id     =             t.system_type_id
INNER JOIN  Sys.Indexes     I
ON  I.object_id =       Tbl.object_id
Inner Join  Sys.sysindexes  X
On  I.index_id      =       X.indid
And I.object_id =       X.id
WHERE       X.rowcnt > 0
ORDER BY    tbl.name