SQL While循环陷入无限循环

时间:2013-07-12 17:05:44

标签: sql sql-server-2008

我正在尝试编写一个简单的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

它似乎正在获取它找到的最后一行的值并保持循环。 有关如何解决此问题的任何建议。

UPDATE:我正在为select语句返回的每个值调用一个存储过程。而不是使用游标编写逻辑。所以实际上试图将光标转换为while循环。 感谢

5 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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 isnull(@colname,'') <> ''

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

无论如何,我认为你的查询有点复杂,以这种方式使用 WHILE

答案 2 :(得分: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

答案 3 :(得分: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

答案 4 :(得分: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