我有一个经常运行更新语句的 SQL Server 数据库。我在 Activity Monitor 上看到这个更新语句触发 27ms,我想改进它。
更新查询是这样的:
UPDATE Code
SET CommissioningFlag = @newCommFlagValue
, Source = @source
, UserName = @username
, LastChange = CAST(SYSDATETIMEOFFSET() as nvarchar(50))
, SentToNextLevel = 0
, HelperCodeId = @helperCodeId
WHERE CodeId = @codeId
视图突出显示的脚本是:
CREATE VIEW dbo.PrintedCodesStatistics
WITH SCHEMABINDING
AS
SELECT AggregationLevelId, COUNT_BIG(*) as CodesPrinted
FROM dbo.Code
WHERE (CommissioningFlag != 255)
GROUP BY AggregationLevelId
GO
CREATE UNIQUE CLUSTERED INDEX [IX_Printed_Statistics]
ON [dbo].[PrintedCodesStatistics]([AggregationLevelId] ASC);
最后,Code
表脚本:
CREATE TABLE [dbo].[Code] (
[CodeId] INT IDENTITY (1, 1) NOT NULL,
[Serial] NVARCHAR (20) NOT NULL,
[AggregationLevelId] TINYINT NOT NULL,
[CommissioningFlag] TINYINT NOT NULL,
[... ]
CONSTRAINT [PK_CODE] PRIMARY KEY CLUSTERED ([CodeId] ASC),
CONSTRAINT [UC_CODE_SERIAL] UNIQUE NONCLUSTERED ([Serial] ASC)
视图是否会减慢更新查询的速度?
索引视图对写入开销的贡献与表上的常规索引一样多,如果不是更多的话。
每次写入基表时,视图上的索引都必须立即更新。
与常规索引一样,需要权衡取舍:如果您的索引合理地减慢速度并显着提高读取性能,则保留它。如果没有,摆脱它。