如何将多个选择语句插入临时表
Posted
技术标签:
【中文标题】如何将多个选择语句插入临时表【英文标题】:How to insert multiple select statements into a temp table 【发布时间】:2015-02-10 20:11:10 【问题描述】:我有三个不同数据的表,我需要插入一个 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.
【问题讨论】:
【参考方案1】:发生错误是因为第一个 select into 语句创建了表,而第二个和第三个语句试图重新创建它。
将第二个和第三个查询改为:
insert into #temp
select..
【讨论】:
【参考方案2】: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
【讨论】:
【参考方案3】:创建一次临时表,然后将其他两个 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;
【讨论】:
【参考方案4】:你可以检查它是否已经存在
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
【讨论】:
谢谢!这有助于我大量执行查询!【参考方案5】:为什么不只写一个插入语句并在插入之前合并表
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
这将帮助您在需要时轻松地在 select 中添加更多表,因为您不再需要为它们添加任何插入语句
【讨论】:
在每个选择语句中,我使用了 group by 和 order by。它会起作用吗。 显示错误为 Msg 1033, Level 15, State 1, Line 14 ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效,除非 TOP 或 FOR XML 是也指定了。 order by 不会工作,group by will,但是如果你想在插入之前进行 order by,你可以在From A
行之后进行
好的,谢谢您的回复。我可以在其他情况下使用它。以上是关于如何将多个选择语句插入临时表的主要内容,如果未能解决你的问题,请参考以下文章
将多个 CASE 语句合并为一个并 SELECT INTO 临时表