我正在編寫一個存儲過程,該存儲過程創建一個臨時視圖,然後基於此臨時視圖執行多個更新。 問題是這個臨時視圖在第一個UPDATE命令(錯誤是「無效的對象名稱」)後無效。存儲過程中的臨時視圖僅在第一次更新時有效
USE [MyDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_MySP]
@passedParam VARCHAR(32)
AS
BEGIN
WITH MyTempView AS
(
SELECT [myTable1].[Id]
FROM [dbo].[myTable1] LEFT JOIN [dbo].[myTable2] ON [myTable1].Id = [myTable2].[DeviceId]
WHERE
--all kind of conditions
)
--The temp view is valid here
UPDATE [dbo].[myTable1]
SET [myTable1].[Ready] = 0, [myTable1].[Reason] = NULL
WHERE
[myTable1].[Id] IN (SELECT [Id] FROM MyTempView)
--The temp view is NO LONGER VALID from this point
UPDATE [dbo].[myTable1]
SET [myTable1].[Reason] = CONCAT([myTable1].[Reason],'Reason 1.')
WHERE
--all kind of conditions
UPDATE [dbo].[myTable1]
SET [myTable1].[Reason] = CONCAT([myTable1].[Reason],'Reason 2.')
WHERE
--all kind of conditions
UPDATE [dbo].[myTable1]
SET [myTable1].[Reason] = CONCAT([myTable1].[Reason],'Reason 3.')
WHERE
--all kind of conditions
UPDATE [dbo].[myTable1]
SET [myTable1].[Reason] = CONCAT([myTable1].[Reason],'Reason 4.')
WHERE
--all kind of conditions
END
這怎麼能解決? 在此先感謝。
CTE不是「臨時視圖」。 _「創建一個臨時表」_ - 你的sp中沒有臨時表創建代碼。 –