2016-11-22 57 views
0

我正在編寫一個存儲過程,該存儲過程創建一個臨時視圖,然後基於此臨時視圖執行多個更新。 問題是這個臨時視圖在第一個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 

這怎麼能解決? 在此先感謝。

+2

CTE不是「臨時視圖」。 _「創建一個臨時表」_ - 你的sp中沒有臨時表創建代碼。 –

回答

1

是臨時視圖將無效,因爲cte的作用域限於第一個更新語句。所以你把結果插入臨時表。並在你想要的程序中使用它。

USE [MyDB] 
    GO 
    SET ANSI_NULLS ON 
    GO 
    SET QUOTED_IDENTIFIER ON 
    GO 
    ALTER PROCEDURE [dbo].[SP_MySP] 
     @passedParam VARCHAR(32) 
    AS 
    BEGIN 
     if object_id('tempdb..#t1') is not null 
     drop table #t1 
      SELECT [myTable1].[Id] into #t1 
      FROM [dbo].[myTable1] LEFT JOIN [dbo].[myTable2] ON [myTable1].Id = [myTable2].[DeviceId] 
      WHERE 


    --The temp view is valid here 
    UPDATE [dbo].[myTable1] 
    SET [myTable1].[Ready] = 0, [myTable1].[Reason] = NULL 
    WHERE 
    [myTable1].[Id] IN (SELECT [Id] FROM #t1) 

    --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 
0

common table expression(CTE)與WITH name創建之前的一個命令是的一部分:

with name 
    ... implement CTE 
update ... 

它有批處理中的任何進一步的命令沒有軸承。

我想你命名你困惑:

  1. MyTempView不是一個視圖
  2. MyTempView不是暫時的(將對其名稱的前綴#
  3. 表和視圖定義(臨時與否)未定義爲with

目前還不清楚你在CTE試圖達到什麼目的,因此不容易建議什麼是更好的方法。

相關問題