虽然循环没有SQL中的计数器 - 帮助

时间:2011-07-26 17:47:51

标签: sql-server printing while-loop

我正在运行以下代码。代码不会循环遍历@result中的所有记录。什么是正确的语法。在这种情况下我使用计数器吗?我希望它具有灵活性,以便打印变量中的所有值。

declare @result varchar(1000)
select @result = item from items

while @result != ''
begin
print @result
end

Select item from items

导致此查询

enter image description here

我从print获得的是一个无限循环,我必须手动停止并打印出来......

small bed
small bed
small bed
small bed

在变量中打印所有值的正确方法是什么。我只谈论文本数据,而不是数字。

3 个答案:

答案 0 :(得分:3)

SET @result = ''

SELECT @result = @result + CHAR(10) + CHAR(13) + Item from Items

PRINT @Result

这就是你所需要的一切。 WHILE循环是多余的。

答案 1 :(得分:2)

这可能很难解释,因为您似乎缺少对SQL /数据库工作方式的基本理解。

您编写的代码只能存储items表中item列的单个值。将varchar(1000)视为您最喜欢的程序语言中的string的等价物。 select @result = ...语句基本上是每行并将@result设置为item,这意味着@result会被下一个值替换(并且在语句结束时,它的内容将是表中的最后一个值)。

通常,您不应该在SQL代码中使用循环。对于任何前端应用程序需要数据,最好留下。当然,也有例外。

我强烈建议阅读有关SQL的入门知识,特别是基于集合的操作与程序操作。

JNK的解决方案可能会为您提供您在这个实例中寻找的内容,但我会首先质疑您到底需要什么类型的解决方案。

答案 2 :(得分:0)

您可以使用游标迭代查询返回的所有数据。

declare a_cursor cursor for select Item from Items
declare @Item varchar(1000)

open a_cursor
fetch next from a_cursor into @Item
while @@fetch_status = 0
begin
     print @Item
     fetch next from a_cursor into @Item
end

close a_cursor
deallocate a_cursor