这是SQL Server的错误。如果从具有聚集的列存储索引的表中删除了列,然后添加了一个具有相同名称的新列,则该列似乎使用了已删除的旧列作为谓词。这是MVCE:
该脚本开始与10000
同排statusId
的1
和statusId2
的5
-然后删除statusID
列,重命名statusId2
到statusId
。因此,最后所有行应statusId
为5。
但是以下查询命中了非聚集索引...
select *
from example
where statusId = 1
and total <= @filter
and barcode = @barcode
and id2 = @id2
...并返回2
行(所选内容statusId
与该WHERE
子句所隐含的内容不同)...
+-------+---------+------+-------+----------+
| id | barcode | id2 | total | statusId |
+-------+---------+------+-------+----------+
| 5 | 5 | NULL | 5.00 | 5 |
| 10005 | 5 | NULL | 5.00 | 5 |
+-------+---------+------+-------+----------+
...而这个访问列存储并正确返回 0
select count(*)
from example
where statusId = 1
MVCE
/*Create table with clustered columnstore and non clustered rowstore*/
CREATE TABLE example
(
id INT IDENTITY(1, 1),
barcode CHAR(22),
id2 INT,
total DECIMAL(10,2),
statusId TINYINT,
statusId2 TINYINT,
INDEX cci_example CLUSTERED COLUMNSTORE,
INDEX ix_example (barcode, total)
);
/* Insert 10000 rows all with (statusId,statusId2) = (1,5) */
INSERT example
(barcode,
id2,
total,
statusId,
statusId2)
SELECT TOP (10000) barcode = row_number() OVER (ORDER BY @@spid),
id2 = NULL,
total = row_number() OVER (ORDER BY @@spid),
statusId = 1,
statusId2 = 5
FROM sys.all_columns c1, sys.all_columns c2;
ALTER TABLE example
DROP COLUMN statusid
/* Now have 10000 rows with statusId2 = 5 */
EXEC sys.sp_rename
@objname = N'dbo.example.statusId2',
@newname = 'statusId',
@objtype = 'COLUMN';
/* Now have 10000 rows with StatusID = 5 */
INSERT example
(barcode,
id2,
total,
statusId)
SELECT TOP (10000) barcode = row_number() OVER (ORDER BY @@spid),
id2 = NULL,
total = row_number() OVER (ORDER BY @@spid),
statusId = 5
FROM sys.all_columns c1, sys.all_columns c2;
/* Now have 20000 rows with StatusID = 5 */
DECLARE @filter DECIMAL = 5,
@barcode CHAR(22) = '5',
@id2 INT = NULL;
/*This returns 2 rows from the NCI*/
SELECT *
FROM example WITH (INDEX = ix_example)
WHERE statusId = 1
AND total <= @filter
AND barcode = @barcode
AND id2 = @id2;
/*This counts 0 rows from the Columnstore*/
SELECT COUNT(*)
FROM example
WHERE statusId = 1;
我还在Azure反馈门户上提出了一个问题:
对于遇到此问题的其他任何人,重建集群列存储索引都可以解决此问题:
alter index cci_example on example rebuild
重建CCI仅修复任何现有数据。如果添加了新记录,则这些记录会再次出现该问题;因此,目前唯一已知的表修复方法是完全重新创建它。