如何插入到 SQL Server 中的现有临时表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20967812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 00:39:00  来源:igfitidea点击:

How to insert into an existing temp table in SQL Server

sqlsql-servertemp-tables

提问by SuicideSheep

I am trying to execute two select statements into a query that pumps data into a temp table. The first query will have 5 columns while the second query will have only one column.

我正在尝试将两个选择语句执行到将数据泵入临时表的查询中。第一个查询将有 5 列,而第二个查询将只有一列。

The first can be achieved by:

第一个可以通过以下方式实现:

Select a.ID AS [a], 
       b.ID AS [b], 
       c.ID AS [c]
INTO #testingTemp
FROM
....

Now I have my second query trying to pump data into #testingTemp:

现在我有我的第二个查询试图将数据泵入#testingTemp

Select z.ID AS [c]
INTO #testingTemp
FROM
....  

But my problem is There is already an object named #testingTemp in the database?

但我的问题是There is already an object named #testingTemp in the database

I tried to search for a solution on the Internet but mostly people are only facing the problem at my first part but apparently nobody trying to expand a temp table on second query?

我试图在互联网上搜索解决方案,但大多数人只在我的第一部分面临问题,但显然没有人试图在第二次查询时扩展临时表?

回答by schliemann

Change it into a insert into statement. Otherwise you create the same temp table multiple times and that is not allowed.

将其更改为 insert into 语句。否则,您多次创建相同的临时表,这是不允许的。

Insert into #testingTemp (a,b,c)
Select a.ID AS [a], 
       b.ID AS [b], 
       c.ID AS [c]
FROM

回答by Luuk

The second query should just be a normal insert.

第二个查询应该只是一个普通的插入。

    INSERT INTO #testingTemp
    (a,
     b,
     c)
   select etc. 

dont forget to drop the temptable when you are done.

完成后不要忘记放下 temptable。

回答by sandiejat

And if you want to insert everything:

如果你想插入所有内容:

INSERT INTO #TempTableName
SELECT * FROM MyTable