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 使用游标编写逻辑。所以实际上试图将光标转换为while循环。谢谢

4

5 回答 5

1

当 SELECT 语句不返回任何行时,不会执行变量 (@colname=colname) 的赋值 - 并且 @colname 的值保持不变 - 非空,来自上一次迭代的值 - 循环将永远继续

您需要在 select 语句之前将 @colname 设置为 null - 或在 select 语句之后立即检查 @@rowcount 以检查是否确实找到了行 - 如果没有 - 退出循环

于 2013-07-14T22:45:17.650 回答
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 回答
0

我不理解你的脚本,但也许这会有用:

declare @colname as varchar =''

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

您的问题出在“While 条件”上,因为 '' <> NULL。也许你也可以这样:

while isnull(@colname,'') <> ''

或者

while coalesce(@colname,'') <> ''

无论如何,我认为您的查询在以这种方式使用它时会更复杂一些

于 2013-07-12T17:14:19.010 回答
0

我的猜测是您正在尝试执行一系列存储过程。这些过程存储在 table1.col1 中。我会做类似以下的事情:

DECLARE @ColName VARCHAR(MAX)
SET @ColName = ''

SELECT @ColName = col1
FROM Table1
WHERE Col1 > @ColName
ORDER BY Col1

While @Colname IS NOT NULL
BEGIN 
EXEC SP(@colname)

SELECT @ColName = col1
FROM Table1
WHERE col1 > @ColName
AND col1 in ('test1', 'test2', 'test3')
ORDER BY col1

END 
于 2013-07-12T17:33:10.343 回答
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 回答