0

我试图在程序结束时像这样实现我需要一个临时表中的所有行我怎样才能做到这一点

if @i > 1
begin
select * from into #tempTbl1 from payments
where method = 'test1'
end 
else
begin
select * from into #tempTbl2 from payments
where method = 'test1'
end

insert into #tempTbl1 select * from #tempTbl2

select * from #tempTbl1
4

2 回答 2

1

尽管存在先前的逻辑问​​题,要简单地从两个临时表中获取所有行,请使用 UNION:

select * from #tempTbl1  
UNION ALL  
SELECT * from #tempTbl2  
于 2013-03-20T08:32:58.990 回答
0

您在这里遇到的问题是,根据您的 IF/ELSE,您将永远不会同时拥有这两个表。您的最终 INSERT INTO 要求两个表都存在。在尝试填充之前,您可能需要先在存储过程中创建对象,然后再插入表中。

这也引出了一个问题,如果您以后要在 #tempTbl1 中插入所有内容,它是在 SELECT INTO 语句中创建的,为什么首先要有 #tempTbl2 ?

create procedure dbo.testing
(@i int)
AS
if @i > 1
    begin
        print 'In condition 1'
        select * 
        into #tempTbl1 
        from payments
        where method = 'test1'
    end 
else
    begin
        print 'In condition 2'
        select * 
        into #tempTbl2 
        from payments
        where method = 'test1'
    end

print 'Made it out of the if else'

insert into #tempTbl1 
select * 
from #tempTbl2

--  Never gets this far...
print 'In the final select'

select * 
from #tempTbl1

如果您致力于此方法,那么您可能需要检查表是否存在:

IF  EXISTS (SELECT * FROM tempdb.sys.objects WHERE object_id = OBJECT_ID(N'tempdb.dbo.#tempTbl1') AND type in (N'U'))
print 'Table is there'

根据评论更新

根据您的评论,这将起作用。您最初发布的 SELECT...INTO 语句允许您根据您选择的列的数据类型创建一个表,但目标表不能已经存在。如果您事先定义了要插入的结构,您可以对这两个条件进行评估并最终得到一个表作为结果。

(注意 - 我的“payments”表只有两列,“method”和“col2”。您需要在 CREATE TABLE 和 SELECT 中指定所需的列)

create procedure dbo.testing
(@i int)
AS
create table #tempTbl1
(method varchar(10)
, col2 int)

if @i > 1
    begin
        insert into dbo.#tempTbl1
        select method, col2 
        from payments
        where method = 'test1'
    end 
else
    begin
        insert into dbo.#tempTbl1
        select method, col2 
        from payments
        where method = 'test1'
    end

select * 
from #tempTbl1
于 2013-03-20T03:03:00.350 回答