0

手順の最後にこのように達成しようとしています 1つの一時テーブルにすべての行が必要です どうすればこれを達成できますか

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 では、両方のテーブルが存在する必要があります。データを入力してからテーブルに挿入する前に、ストアド プロシージャで事前にオブジェクトを作成する必要がある場合があります。

SELECT INTO ステートメントで作成された #tempTbl1 に後ですべてを挿入する場合、なぜ最初に #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 ステートメントを使用すると、選択元の列のデータ型に基づいてテーブルを作成できますが、宛先テーブルがまだ存在していてはなりません。挿入先の構造を事前に定義しておくと、2 つの条件を評価して結果として 1 つのテーブルにすることができます。

(注 - 私の「支払い」テーブルには、「メソッド」と「col2」の 2 つの列しかありませんでした。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 に答える