0

シンプルな while ループを書こうとしています。

declare @colname as varchar =''

while @colname is not null
begin
  Select @colname = col1
  FROM Table1
  WHERE col1 in ('test1','test2','test3')

  if(@colname is not null)
   begin
    exec sp('@colname')
   end

end

見つけてループし続ける最後の行の値を取得しているようです。これを修正する方法に関する提案。

更新: select ステートメントによって返される値ごとにストアド プロシージャを呼び出しています。ロジックがカーソルを使用して書かれている間ではなく。したがって、実際にはカーソルをwhileループに変換しようとしています。ありがとう

4

5 に答える 5

0

しかし、本当にこの種のことをする必要がある場合、ループから抜け出したい場合は、これを試してください:

declare @colname as varchar =''

while @colname is not null
begin
Select @colname = col1
FROM Table1
WHERE col1 in ('test1','test2','test3')
Select @colname = null
end

編集 :

@rsはほとんどそれを持っていました。

これを試して :

declare @t table (colname varchar(10))
insert into @t
select distinct col1
FROM Table1
WHERE col1 in ('test1','test2','test3')

declare @colname as varchar(10) =''
while @colname is not null
begin
  -- get one row from table variable
  Select top 1 @colname = colname
  FROM @t

  --execute stored procedure
  exec sp('@colname')

  --delete row from table variable so that you don't read it again
  delete from @t where colname = @colname
  --set @colname to null if there is no more value to process
if ((select count(*) from @t) = 0)
begin
select @colname = null
end
end
于 2013-07-12T17:23:47.540 に答える
0

これを試して

declare @t table (colname varchar(10))
insert into @t
select distinct col1
FROM Table1
WHERE col1 in ('test1','test2','test3')

declare @colname as varchar =''
declare @cnt int = 0;

--set count used in loop condition
select @cnt = count(*) from @t

while @cnt > 0
begin
  -- get one row from table variable
  Select top 1 @colname = colname
  FROM @t

  --execute stored procedure
  if(@colname is not null)
   begin
    exec sp('@colname')
   end

  --delete row from table variable so that you don't read it again
  delete from @t where colname = @colname

  select @cnt = count(*) from @t
end
于 2013-07-12T17:29:09.473 に答える