如何将多个select语句插入临时表

时间:2014-12-12 06:36:37

标签: sql sql-server database sql-server-2008 select

我有三个包含不同数据的表,我需要插入一个TEMP表并在StoredProcedure中返回该表。

我试过:

-- To get last 10 Days Letters count
SELECT col1,col2,1 AS Type, LettersCount
INTO #temp FROM tblData

-- To get last 4 weeks Letters count
SELECT col1,col2,2 AS Type, LettersCount
INTO #temp FROM tblData

-- To get month wise Letters count
SELECT col1,col2,3 AS Type, LettersCount
INTO #temp FROM tblData

将错误显示为

Msg 2714, Level 16, State 1, Line 16
There is already an object named '#temp ' in the database.
Msg 102, Level 15, State 1, Line 24
Incorrect syntax near 'T'.
Msg 2714, Level 16, State 1, Line 32
There is already an object named '#temp ' in the database.

5 个答案:

答案 0 :(得分:20)

您可以检查它是否已存在

IF OBJECT_ID ('tempdb..#TempLetters') is not null
drop table #TempLetters


SELECT col1,col2,1 AS Type, LettersCount
INTO #TempLetters FROM tblData

-- To get last 4 weeks Letters count
INSERT INTO #TempLetters
SELECT col1,col2,2 AS Type, LettersCount
FROM tblData

-- To get month wise Letters count
INSERT INTO #TempLetters
SELECT col1,col2,3 AS Type, LettersCount
FROM tblData

答案 1 :(得分:4)

SELECT INTO语句也可以用于使用另一个的模式创建一个新的空表 select * into tablename from ..此处 tablename 表不应存在。

像这样更改插入内容:

SELECT col1,
       col2,
       1 AS Type,
       LettersCount
INTO   #temp
FROM   tblData

-- To get last 4 weeks Letters count
INSERT INTO #temp
SELECT col1,col2,2 AS Type,LettersCount
FROM   tblData

-- To get month wise Letters count
INSERT INTO #temp
SELECT col1,col2,3 AS Type,LettersCount
FROM   tblData 

答案 2 :(得分:4)

创建一次临时表,然后插入其中两个SELECT语句:

SELECT col1, col2, 1 AS Type, LettersCount
  INTO #temp
  FROM tblData;

INSERT INTO #temp
    SELECT col1, col2, 2 AS Type, LettersCount
      FROM tblData;

INSERT INTO #temp
    SELECT col1, col2, 3 AS Type, LettersCount
      FROM tblData;

答案 3 :(得分:2)

为什么不在insert

之前只编写一个insert语句并将表联合起来
with A as
(
    -- To get last 10 Days Letters count
    SELECT col1,col2,1 AS Type, LettersCount
    FROM tblData
    union all
    -- To get last 4 weeks Letters count
    SELECT col1,col2,2 AS Type, LettersCount
    FROM tblData
    union all
    -- To get month wise Letters count
    SELECT col1,col2,3 AS Type, LettersCount
    FROM tblData
)
select col1, col2, Type, LettersCount
INTO #temp 
FROM A

如果您需要,这将有助于您轻松地在选择中添加更多表格,因为您不再需要它们的插入语句

答案 4 :(得分:1)

发生错误是因为第一个select into语句创建了表,第二个和第三个尝试再次重新创建它。

将第二个和第三个查询更改为:

insert into #temp
select..