如何创建存储过程以将数据从查询复制到临时 table?

How to create a stored procedure to copy data from a query to a temporary table?

我需要将数据从现有 table/query 插入临时 table。以下会产生下面详述的错误。

CREATE TABLE SPTemporary
AS
BEGIN
    SELECT * into #temppT
        FROM SampleTable
END

引发此错误:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'begin'.

更正语法,使用 procedure 而不是 table :

create procedure SPTemporay
as
begin
select * into #temppT
from SampleTable
end

但是,如果您只需要数据副本,那么只需要子查询就足够了:

select st.* into #temppT
from SampleTable st

我觉得语法不对,应该是这样的:

create table SPTemporay
as
select * from SampleTable

希望对您有所帮助。

一种方法是:

select st.*
into SPTemporay
from SampleTable st

一个select只能把数据放在一个table中。不清楚您真正想要 SPTemporary 还是 #temppT。如果您确实需要两次 table 中的相同数据,您可以重复 select

编辑:

如果你想要一个存储过程,你可以这样做:

create procedure SPTemporay
as begin
    select *
    into #temppT
    from SampleTable
end;

这是相当无意义的,因为临时 table 在存储过程 returns 时被丢弃。