2011-03-11 87 views
-1

以下是我的示例存儲過程。當我通過傳遞DATE執行存儲過程時,它顯示的錯誤如下。在SQL SERVER 2005中執行存儲過程時出錯

無效的對象名稱TEMPP「

- 存儲過程

ALTER PROCEDURE [dbo].[mystoredprocedure] 
@abc DATETIME //coming fron front-end 
AS 
BEGIN 
SET NOCOUNT ON; 

WITH TEMPP AS 
( 
SELECT DISTINCT(ID), NAME 
FROM EMPLOYEE WHERE EMPDATE > @abc 
) 
    select DP.NAME INTO xy from DEPARTMENT DP,TEMPP TE 
    where DP.ID=TE.ID ; 

SELECT * FROM xy; 
DROP xy; 
END 

哪裏是錯誤的?

問候,

JN

+0

可能重複:http://stackoverflow.com/questions/954016/multiple-select-statements-using-sql-server-2005-with-statement – Bravax 2011-03-11 08:25:09

+0

我不這麼認爲 - CTE是隻用一旦。 – Goran 2011-03-11 08:27:25

+0

順便說一句。如果您將select(使用@gbn建議)重寫入連接,錯誤是否仍然存在? – Goran 2011-03-11 08:29:51

回答

0

從書本在線: 下列物品不得在遞歸成員的CTE_query_definition:

SELECT DISTINCT [...]

你可以試試這個:

ALTER PROCEDURE [dbo].[mystoredprocedure] 
@abc DATETIME //coming fron front-end 
AS 
BEGIN 
SET NOCOUNT ON; 

    select DP.NAME from DEPARTMENT DP 
    inner join 
    (
     SELECT DISTINCT(ID), NAME 
     FROM EMPLOYEE WHERE EMPDATE > @abc 
    )TE ON DP.ID=TE.ID; 

END 
+0

OP代碼中沒有遞歸成員。 – Goran 2011-03-11 08:39:41

+0

好的。解決辦法是什麼? – sriramjitendra 2011-03-11 11:45:57

0

如果您的ID是您的主鍵,則它已經是DISTINCT,這意味着如果@ibram answer是您錯誤的原因,您可以將其刪除。我認爲xy應該是一個臨時表,並且不能看到它的任何用處。

ALTER PROCEDURE [dbo].[mystoredprocedure] 
    @abc DATETIME //coming fron front-end 
AS 
BEGIN 

SET NOCOUNT ON; 

WITH TEMPP AS 
( 
    SELECT ID, NAME 
    FROM EMPLOYEE WHERE EMPDATE > @abc 
) 
SELECT DP.NAME 
FROM DEPARTMENT DP 
JOIN TEMPP TE 
    ON DP.ID=TE.ID ; 

END 
0

通常,你會看到這個錯誤,如果你嘗試,並在過程中稍後引用CTE。只有在其定義之後立即生效。

ALTER PROCEDURE [dbo].[mystoredprocedure] @abc DATETIME 
AS 
    BEGIN 
     SET NOCOUNT ON; 

     WITH TEMPP 
      AS (SELECT DISTINCT (name), 
           number 
       from master..spt_values) 
     select number 
     INTO xy 
     from TEMPP; 

     SELECT * 
     FROM xy; 

     DROP table xy; 

    SELECT * FROM TEMPP /*Not Allowed: Throws this error*/ 
    END