2016-03-30 8 views
-2

別のテーブルに挿入された1つの行に別のクエリの行を挿入する必要があります。 1つの行だけが返された場合に動作します。ただし、行数が1より大きい場合は失敗します。私はforループを理解できません - - **セクションで示されています。sql forループには、SQLインサートの一部として返された値が含まれています

declare @cn as int, @i as int 
set @cn = 569 
declare @dM table(dM varchar(max)) 
declare @rowNum table (rowNum int) 
set @i = 1 

insert @rowNum 
exec ('select count(*) from table1 where c = ' + @cn) 
--select rowNum from @rowNum as NumberRows --return 2 rows 

if (select rowNum from @rowNum as NumberRows) > 1 
begin 
insert @dM 
exec ('select d.d + '' '' + o.o + '' '' + d.v as rtM from table1 where c = ' + @countNumber) 
--returns 2 rows as rtM so there will be two inserted rows 
--going now okay 
--going later okay 

--** 
while (@i <= (select count(*) from @rowNum)) --didn't work 
--for each row returned in rtM in need to include as part of the overall insert 
insert into table2 (cn, rtM, idate) 
select 
@cn 
,'Message is: ' + (select dM from @dM) + ' - the message.' 
cz.idate + ' ' + qw.txt 
from table3 as cz 
inner join table4 as qw on cz.id = qw.id 
where cz.cn = @cn 
set @i = @i + 1 
--** 
end 
else 
begin 
--there is only 1 row returned from rtM so there will be a single inserted row 
insert @dM 
exec ('select d.d + '' '' + o.o + '' '' + d.v as rtM from table where c = ' + @countNumber) 
insert into table2 (cn, rtM, idate) 
select 
@cn 
,'Message is: ' + (select dM from @dM) + ' - the message.' 
cz.idate + ' ' + qw.txt 
from table3 as cz 
inner join table4 as qw on cz.id = qw.id 
where cz.cn = @cn 
end 
+1

何が間違っているのか分かりませんが、@rowNumをINTにして、table1のcount()と同じ値に設定してください。 – JamieD77

+0

@rowNumはテーブルが保存されていますdMクエリで検出された行の数。 – wl2m

+0

私は次のように変更しました:@ i = 0を設定するために@i = 0を設定して、コードを実行して、dM行が2であるところの次のコードを取得しました。 =、!=、<, <= , >、> =、またはサブクエリが式として使用されている場合は、これは許可されません – wl2m

答えて

0

ここでは、dynamic sqlが意味をなさない場合の例を示します。

INSERT @dM 
EXEC ('SELECT d.d + '' '' + o.o + '' '' + d.v AS rtM FROM table1 WHERE c = ' + @countNumber) 

これは、このように動的SQLなしで書き直すことができます。

INSERT @dM 
SELECT d.d + ' ' + o.o + ' ' + d.v as rtM FROM table1 WHERE c = @countNumber 

ここでの大きな問題は、ここでの質問は単純にここでは動作しないことです。動的SQLまたはこれは無効です。 dという名前のオブジェクトまたは別名を参照していますが、oという名前の別名も参照していますが、どちらもクエリにはありません。

+0

ああスナップ - それらは私が含めるのを忘れた結合の一部です。 – wl2m

+0

私は動的SQLを削除しました。どのようにループを各行に移動し、2つの行を挿入する挿入ステートメントに追加することができますか? – wl2m

+0

どのようなループですか?あなたが投稿したコードのどこにでもループはありません。列としてサブクエリの代わりに最終的な選択を行うときは、別の結合を使用する必要があります。 –

関連する問題