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

我有一个现有的查询,输出当前的数据,我想插入到一个临时表,但有一些问题,这样做。有人知道该怎么做吗?

这里有一个例子

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%','%')到一个临时表?

867917 次浏览

你可以这样做:

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

只要确保列在数量和数据类型上都是匹配的。

最快的方法是使用“ SELECTINTO”命令,例如。

SELECT * INTO #TempTableName
FROM....

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

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%',
'%')

SQLServerR22008需要如下 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

试试这个:

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

请对 x 使用别名,这样就不会使脚本和结果失败。

就我个人而言,我需要有人帮我弄清楚如何使用它,它真的非常非常棒。

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
SELECT * INTO #TempTable
FROM SampleTable
WHERE...


SELECT * FROM #TempTable
DROP TABLE #TempTable

这是可能的。 试试这样:

Create Global Temporary Table
BossaDoSamba
On Commit Preserve Rows
As
select ArtistName, sum(Songs) As NumberOfSongs
from Spotfy
where ArtistName = 'BossaDoSamba'
group by ArtistName;

作为查询的结尾使用

选择 * into # temp (select * from table1,table2)作为 temp _ table