使用查询将数据插入临时表


144

我有一个输出当前数据的现有查询,我想将其插入到Temp表中,但是这样做有一些问题。有人会对如何执行此操作有一些见解吗?

这是一个例子

SELECT *
FROM  (SELECT Received,
              Total,
              Answer,
              ( CASE
                  WHEN application LIKE '%STUFF%' THEN 'MORESTUFF'
                END ) AS application
       FROM   FirstTable
       WHERE  Recieved = 1
              AND application = 'MORESTUFF'
       GROUP  BY CASE
                   WHEN application LIKE '%STUFF%' THEN 'MORESTUFF'
                 END) data
WHERE  application LIKE isNull('%MORESTUFF%', '%') 

这似乎当前以我需要的方式输出我的数据,但我想将其传递到临时表中。我的问题是我对SQL查询还很陌生,还无法找到一种方法。或者,即使有可能。如果不可能,是否有更好的方法将我要查找的数据获取WHERE application LIKE isNull('%MORESTUFF%','%')到临时表中?


2
#temp已经存在的表中,还是需要创建一个新表?
马丁·史密斯

1
@MartinSmith-它将是一个新的。
scapegoat13年

1
LIKE ISNULL('%MORESTUFF%', '%')将始终与相同LIKE '%MORESTUFF%',不是吗?由于'%MORESTUFF%'(字符串文字)永远不会为null?
gnud

Answers:


187
SELECT *
INTO #Temp
FROM

  (SELECT
     Received,
     Total,
     Answer,
     (CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) AS application
   FROM
     FirstTable
   WHERE
     Recieved = 1 AND
     application = 'MORESTUFF'
   GROUP BY
     CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) data
WHERE
  application LIKE
    isNull(
      '%MORESTUFF%',
      '%')

148

SQL Server R2 2008需要以下AS子句:

SELECT * 
INTO #temp
FROM (
    SELECT col1, col2
    FROM table1
) AS x

查询失败,没有AS x结尾。


编辑

使用SS2016时也需要它,必须添加as t到最后。

 Select * into #result from (SELECT * FROM  #temp where [id] = @id) as t //<-- as t

5
有趣。我只是有同样的问题。最后添加“ As [x]”使一切正常。为什么是这样?
Godfathr

5
@godfathr这是因为from子句正在使用派生表
wootscootinboogie

35

最快的方法是使用“ SELECT INTO”命令,例如

SELECT * INTO #TempTableName
FROM....

这将创建一个新表,您不必事先创建它。


是否可以向#TempTableName添加列?
FrenkyB

@FrenkyB是的,一旦创建了表,您就可以使用ALTER TABLE ADD COLUMN语句
Yuriy Galanter

12

就个人而言,我需要一点点的努力来弄清楚如何使用它,它确实很棒。

IF(OBJECT_ID('tempdb..#TEMP') IS NOT NULL) BEGIN DROP TABLE #TEMP END
        SELECT *
            INTO #TEMP
            FROM (
            The query you want to use many times
            ) AS X

SELECT * FROM #TEMP WHERE THIS = THAT
SELECT * FROM #TEMP WHERE THIS <> THAT
SELECT COL1,COL3 FROM #TEMP WHERE THIS > THAT

DROP TABLE #TEMP

8

您可以这样做:

INSERT INTO myTable (colum1, column2)
SELECT column1, column2 FROM OtherTable;

只要确保这些列是匹配的,它们的数量和数据类型都一样。


5

试试这个:

SELECT *
INTO #Temp
FROM 
(select * from tblorders where busidate ='2016-11-24' and locationID=12
) as X

请对x使用别名,以免脚本和结果失败。



2

这个有可能。尝试这种方式:

Create Global Temporary Table 
BossaDoSamba 
On Commit Preserve Rows 
As 
select ArtistName, sum(Songs) As NumberOfSongs 
 from Spotfy 
    where ArtistName = 'BossaDoSamba'
 group by ArtistName;
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.