2014-11-03 102 views
0

我有一個複雜的SQL查詢可以工作。這就像SQL Select Into #Temp

SELECT * FROM Site s 
    JOIN (
     SELECT DISTINCT z.Value FROM Doc z 
     JOIN (
      SELECT x.DocumentID FROM Doc x 
      JOIN (
       SELECT DocumentID, MAX(VERSION) AS VERSION 
       FROM Doc GROUP BY DocumentID) y ON y.DocumentID = x.DocumentID 
      WHERE DocumentTypeID = 78 AND MetadataTypeID = 22 AND VALUE > GETDATE() AND y.Version = x.Version 
      ) a ON z.DocumentID = a.DocumentID 
     WHERE MetadataTypeID = 2 
    ) b ON b.Value = s.SiteID 
    WHERE SiteID > 0 

它做我想做的事情。但是,當我把它包在

SELECT * INTO #Temp FROM() 

我得到一個不正確的語法附近「)」。

我很困惑。我只是想將結果放入臨時表中,以便我可以對其進行進一步處理。爲什麼它不起作用?

+6

AS了' – Lamak 2014-11-03 18:00:03

+2

嘗試'SELECT * INTO #TEMP FROM()。感謝你們的快速回答。 – RBarryYoung 2014-11-03 18:00:12

+0

尼斯使用別名,'SELECT * INTO #TEMP FROM()AS A' – erosebe 2014-11-03 18:01:50

回答

2

您錯過了子查詢的別名。

SELECT * INTO #MyTempTable 
FROM 
(
SELECT * FROM Site s 
    JOIN (
     SELECT DISTINCT z.Value FROM Doc z 
     JOIN (
      SELECT x.DocumentID FROM Doc x 
      JOIN (
       SELECT DocumentID, MAX(VERSION) AS VERSION 
       FROM Doc GROUP BY DocumentID) y ON y.DocumentID = x.DocumentID 
      WHERE DocumentTypeID = 78 AND MetadataTypeID = 22 AND VALUE > GETDATE() AND y.Version = x.Version 
      ) a ON z.DocumentID = a.DocumentID 
     WHERE MetadataTypeID = 2 
    ) b ON b.Value = s.SiteID 
    WHERE SiteID > 0 
) AS DT 
1
select * into TBL_name from 
(SELECT * FROM Site s 
    JOIN (
     SELECT DISTINCT z.Value FROM Doc z 
     JOIN (
      SELECT x.DocumentID FROM Doc x 
      JOIN (
       SELECT DocumentID, MAX(VERSION) AS VERSION 
       FROM Doc GROUP BY DocumentID) y ON y.DocumentID = x.DocumentID 
      WHERE DocumentTypeID = 78 AND MetadataTypeID = 22 AND VALUE > GETDATE() AND y.Version = x.Version 
      ) a ON z.DocumentID = a.DocumentID 
     WHERE MetadataTypeID = 2 
    ) b ON b.Value = s.SiteID 
    WHERE SiteID > 0)al