【发布时间】:2011-07-13 15:40:10
【问题描述】:
我有这样的事情
create function Answers_Index(@id int, @questionID int)
returns int
as begin
return (select count([ID]) from [Answers] where [ID] < @id and [ID_Question] = @questionID)
end
go
create table Answers
(
[ID] int not null identity(1, 1),
[ID_Question] int not null,
[Text] nvarchar(100) not null,
[Index] as [dbo].[Answers_Index]([ID], [ID_Question]),
)
go
insert into Answers ([ID_Question], [Text]) values
(1, '1: first'),
(2, '2: first'),
(1, '1: second'),
(2, '2: second'),
(2, '2: third')
select * from [Answers]
效果很好,但它往往会降低查询速度。如何使列Index 保持不变?我试过以下:
create table Answers
(
[ID] int not null identity(1, 1),
[ID_Question] int not null,
[Text] nvarchar(100) not null,
)
go
create function Answers_Index(@id int, @questionID int)
returns int
with schemabinding
as begin
return (select count([ID]) from [dbo].[Answers] where [ID] < @id and [ID_Question] = @questionID)
end
go
alter table Answers add [Index] as [dbo].[Answers_Index]([ID], [ID_Question]) persisted
go
insert into Answers ([ID_Question], [Text]) values
(1, '1: first'),
(2, '2: first'),
(1, '1: second'),
(2, '2: second'),
(2, '2: third')
select * from [Answers]
但这会引发以下错误:Computed column 'Index' in table 'Answers' cannot be persisted because the column does user or system data access. 或者我应该忘记它并使用[Index] int not null default(0) 并将其填充到on insert 触发器中?
编辑:谢谢,最终解决方案:
create trigger [TRG_Answers_Insert]
on [Answers]
for insert, update
as
update [Answers] set [Index] = (select count([ID]) from [Answers] where [ID] < a.[ID] and [ID_Question] = a.[ID_Question])
from [Answers] a
inner join [inserted] i on a.ID = i.ID
go
【问题讨论】:
-
老实说,我不完全确定我理解您要解决的问题 - 选择查询慢吗?它不会触及您的“索引”列,所以我看不出这有什么关系 - 尽管您可能想要添加一个或两个索引......
标签: sql-server calculated-columns