用触发器替换视图
我有一个视图,我希望创建一个失败的索引,因为我需要对计算列进行索引(这会失败,错误代码 2729“...不能在索引或统计信息中使用或用作分区键,因为它是不确定的”。我希望能够用一个触发器或一组触发器替换视图,这些触发器将维护一个索引表。视图非常简单。
给定一个表:
CREATE TABLE SourceData (
ItemId int NOT NULL,
KeyId int NOT NULL,
Value varchar(MAX) NULL
)
我创建了视图:
CREATE VIEW DateView WITH SCHEMABINDING
AS
SELECT CONVERT(DATETIME, Value) As KeyDate,
ItemId FROM dbo.SourceData WHERE KeyId=123
然后我尝试在视图上创建索引:
CREATE NONCLUSTERED INDEX IX_DateView ON dbo.DateView (
[KeyDate] ASC
)
INCLUDE ( [ItemId])
这失败了,
我以前没有真正使用过触发器,但我知道我应该能够使用它们来检测和过滤对底层 SourceData 表的任何更改,并将它们应用到新表中以进行替换。日期视图
I have a view which I was hoping to create an index over which is failing because I would need to index a computed column (this fails with error code 2729 "...cannot be used in an index or statistics or as a partition key because it is non-deterministic". I am hoping to be able to replace the view with a trigger or set of triggers which would maintain an indexed table to . The view is quite simple.
Given a table:
CREATE TABLE SourceData (
ItemId int NOT NULL,
KeyId int NOT NULL,
Value varchar(MAX) NULL
)
I created the view:
CREATE VIEW DateView WITH SCHEMABINDING
AS
SELECT CONVERT(DATETIME, Value) As KeyDate,
ItemId FROM dbo.SourceData WHERE KeyId=123
I then try to create an index on the view:
CREATE NONCLUSTERED INDEX IX_DateView ON dbo.DateView (
[KeyDate] ASC
)
INCLUDE ( [ItemId])
which fails.
I haven't really used triggers before, but I understand I should be able to use them to detect and filter any changes to the underlying SourceData table and apply them to a new table to replace the DateView
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将 KeyDate 实现为真实日期时间列,并使用触发器维护它(在插入和更新时)
将该列添加为真实日期时间
创建触发器来维护它
创建视图
现在这将起作用
You can materialize the KeyDate as a real datetime column, and maintain it using a trigger (on insert and update)
Add the column as a real datetime
Create a trigger to maintain it
Create the view
Now this will work