将SQL查询结果转换为临时表

时间:2018-07-13 14:12:14

标签: sql sql-server temp-tables

我试图将我的sql结果转换为临时表,但它不断返回以下错误:

  

期望为As或Id或带引号的ID。

我知道sql结果正确,但是当我添加SELECT * INTO #newtable FROM时,sql查询不起作用。 怎么了?

SELECT *
INTO #newtable
FROM 
    (
    SELECT
        Url,Id 
    FROM Blob 
    WHERE 
        Id IN 
            (
            SELECT 
                BlobId 
            FROM 
                XrefBlobProjectMeeting
            ) 
        AND Extension NOT IN ('xlsx','xls','avi','jpg','mp4','wmv','png')
        AND (RefContentTypeId IN (11,13,14,35))
    )

2 个答案:

答案 0 :(得分:1)

不确定为什么要嵌套SELECT。这是您更有可能执行的操作,因为您不必为子查询加上别名:

SELECT Url,
       Id
INTO #newtable
FROM Blob
WHERE Id IN (SELECT BlobId FROM XrefBlobProjectMeeting)
  AND Extension NOT IN ('xlsx', 'xls', 'avi', 'jpg', 'mp4', 'wmv', 'png')
  AND (RefContentTypeId IN (11, 13, 14, 35));

不过,您最好将IN更改为EXISTS

SELECT [Url],
       Id
INTO #newtable
FROM Blob B
WHERE EXISTS (SELECT 1
              FROM XrefBlobProjectMeeting E
              WHERE E.BlobID = B.ID)
  AND Extension NOT IN ('xlsx', 'xls', 'avi', 'jpg', 'mp4', 'wmv', 'png')
  AND RefContentTypeId IN (11, 13, 14, 35);

答案 1 :(得分:1)

我仅以您的方式尝试了您的问题,它对我有用。解决方案如下所示;

SELECT Url,Id
INTO #newtable
    FROM Blob 
    WHERE 
        Id IN 
            (
            SELECT 
                BlobId 
            FROM 
                XrefBlobProjectMeeting
            ) 
        AND Extension NOT IN ('xlsx','xls','avi','jpg','mp4','wmv','png')
        AND (RefContentTypeId IN (11,13,14,35))