SQL选择#Temp

时间:2014-11-03 17:58:37

标签: sql sql-server temp

我有一个复杂的SQL查询。就像

    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 ()

我在')'附近的语法不正确。

我很困惑。我只想将结果放入临时表中,以便我可以进一步开展工作。为什么不起作用?

2 个答案:

答案 0 :(得分: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 :(得分: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