Sql-Server
計算表中的總行數 - 當它是堆時失敗 - 有什麼解決辦法嗎?
我有一個程序可以用來找出一張桌子有多大。
select * from sys.objects where name = 'WMS_SLALoad' -- to get the object_id of my table -- in this case it is 2041058307 SELECT o.object_id, s_name=s.name, o.name, ddps.row_count ,[Statistics_Updated]=STATS_DATE(I.OBJECT_ID,I.INDEX_ID) FROM sys.indexes AS i INNER JOIN sys.objects AS o ON i.OBJECT_ID = o.OBJECT_ID INNER JOIN sys.schemas s ON s.schema_id = o.schema_id INNER JOIN sys.dm_db_partition_stats AS ddps ON i.OBJECT_ID = ddps.OBJECT_ID AND i.index_id = ddps.index_id WHERE i.index_id < 2 and o.object_id = 2041058307 go
但是當我從那個表中選擇時,總是少了 7 行。我的計數總是告訴我該表比實際多 7 行。
我認為可能是這種情況,這實際上不是一個表,它是一個堆,因為它沒有任何索引,正如您在下面的腳本中看到的那樣。
CREATE TABLE [dbo].[WMS_SLALoad]( [MessageCycleNumber] [int] NOT NULL, [Timestamp] [varchar](50) NOT NULL, [Warehouse] [varchar](20) NOT NULL, [ProdID] [varchar](8) NOT NULL, [QuantityChange] [int] NOT NULL, [Sign] [char](1) NOT NULL, [Status] [varchar](20) NOT NULL, [ReasonCode] [char](2) NULL, [InUse] [int] NULL CONSTRAINT [DF_WMS_SLALoad_InUse] DEFAULT (0) ) ON [PRIMARY]
如何確保我的腳本給我正確的行數,無論對像是表還是堆?
使用Dan Guzman 評論中提到 的DBCC UPDATEUSAGE 產生了以下結果:
DBCC UPDATEUSAGE(N'WMSData',N'dbo.WMS_SLALoad') WITH COUNT_ROWS
之後,我最初選擇的結果對於我的目的來說已經足夠準確了。