Sql-Server

臨時表的統計資訊

  • November 19, 2018

快速而簡單…為什麼當我嘗試檢索臨時表中某一列的統計資訊時,這個 sp 會失敗?

CREATE PROCEDURE dbo.Demo
AS
BEGIN
SET NOCOUNT ON
-- Declare table variable
CREATE TABLE #temp_table (ID INT)
DECLARE @I INT = 0

-- Insert 10K rows
   WHILE @I < 100
   BEGIN
       INSERT INTO #temp_table VALUES (@I)

       SET @I=@I+1
   END

-- Display all rows and output execution plan (now the EstimateRow is just fine!)
SELECT * FROM #temp_table

-- Is the object there
SELECT OBJECT_ID('tempdb..#temp_table')

-- How about statistics
DBCC SHOW_STATISTICS ('tempdb..#temp_table', 'id')
END;

我不明白,我收到一條消息說沒有在列 id 上創建統計資訊

Could not locate statistics 'id' in the system catalogs.

話雖如此,我看過 Paul White 的一篇文章,其中使用了這種技術並且確實有效。

https://sqlkiwi.blogspot.com/2012/08/temporary-tables-in-stored-procedures.html

有任何想法嗎?

您需要顯式創建一個名為id

CREATE PROCEDURE dbo.Demo
AS
BEGIN
SET NOCOUNT ON
-- Declare table variable
CREATE TABLE #temp_table (ID INT)
DECLARE @I INT = 0

CREATE STATISTICS id ON #temp_table (ID)

-- Insert 10K rows
   WHILE @I < 100
   BEGIN
       INSERT INTO #temp_table VALUES (@I)

       SET @I=@I+1
   END

-- Display all rows and output execution plan (now the EstimateRow is just fine!)
SELECT * FROM #temp_table

-- Is the object there
SELECT OBJECT_ID('tempdb..#temp_table')

-- How about statistics
DBCC SHOW_STATISTICS ('tempdb..#temp_table', 'id')
END;

EXEC dbo.Demo

當留給自己的設備時,系統創建的統計對像有奇怪的名字,比如_WA_Sys_00000002_5F141958

請注意,當您創建統計資訊時 -如果您希望它顯示任何內容,或者可能將您的查詢更改為需要更新統計資訊,您需要CREATE STATISTICS在使用數據填充臨時表之後將命令移動到,例如.SELECT * FROM #temp_table WHERE ID > 0

引用自:https://dba.stackexchange.com/questions/173966