在我的数据库中,我有两个表 Items(Id, ..., ToatlViews int) 和 ItemViews (id, ItemId, Timestamp)
在 ItemViews 表中,我存储了一个项目的所有视图,因为它们来到了站点。有时我想调用一个存储过程来更新 Items.ToatlViews 字段。我尝试使用游标来执行此 SP ...但更新语句是错误的。你能帮我改正吗?我可以在没有光标的情况下执行此操作吗?
CREATE PROCEDURE UpdateItemsViews
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @currentItemId int
DECLARE @currentItemCursor CURSOR
SET @currentItemCursor = CURSOR FOR SELECT Id FROM dbo.Items
OPEN @currentItemCursor
FETCH NEXT FROM @currentItemCursor INTO @currentItemId
WHILE @@FETCH_STATUS = 0
BEGIN
Update dbo.Items set TotalViews = count(*)
from dbo.ItemViews where ItemId=@currentItemId
FETCH NEXT FROM @currentItemCursor INTO @currentItemId
END
END
GO