SQL 中没有计数器的 While 循环 - 帮助
我正在运行以下代码。该代码不会循环遍历@result 中的所有记录。正确的语法是什么。在这种情况下我必须使用计数器吗?我希望它灵活,以便它打印变量中的所有值。
declare @result varchar(1000)
select @result = item from items
while @result != ''
begin
print @result
end
Select item from items
导致此查询
我从打印中得到的是一个无限循环,我必须手动停止它打印这个...
small bed
small bed
small bed
small bed
什么是打印变量中所有值的好方法。我只讨论文本数据,而不是数字。
I am running the following code. The code does not loop through all the records that are there in the @result. What is the correct syntax. Do I have to use counter in this case? I want it to be flexible so it print all values that are there in the variable.
declare @result varchar(1000)
select @result = item from items
while @result != ''
begin
print @result
end
Select item from items
result in this query
What I am getting from print is an endless loop that I have to manually stop and it prints this ...
small bed
small bed
small bed
small bed
What is decent way to print all values in the variable. I am talking about text data only, not numbers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是你所需要的。
WHILE
循环是多余的。That's all you need. The
WHILE
loop is superfluous.这可能很难解释,因为您似乎缺少对 SQL/数据库工作方式的基本了解。
您编写的代码只能存储 items 表中 item 列的单个值。将
varchar(1000)
想象为您最喜欢的过程语言中的string
的等价物。select @result = ...
语句本质上是转到每一行并将 @result 设置为 item,这意味着 @result 不断被下一个值替换(并且,在语句结束时,它是内容将是表中的最后一个值)。一般来说,您不应该在 SQL 代码中使用循环。最好将其留给任何需要数据的前端应用程序。当然,也有例外。
我强烈建议阅读有关 SQL 的入门读物,特别是基于集合的操作与过程操作的入门书。
JNK 的解决方案可能会为您提供在这种情况下所需的内容,但我会质疑您首先需要这种类型的解决方案的目的是什么。
This might be difficult to explain, because it appears you're missing a fundamental understanding of the way SQL/databases work.
The code you wrote can only store a single value of the item column from the items table. Think of a
varchar(1000)
as the equivalent of astring
in your favorite procedural language. Theselect @result = ...
statement is essentially going to each row and setting @result to item, which means @result keeps getting replaced with the next value (and, upon conclusion of the statement, it's contents will be the last value in the table).In general, you shouldn't be using loops in SQL code. That is best left for whatever front-end application needs the data. Of course, there are exceptions.
I would strongly suggest reading a primer on SQL, particularly on set-based operations vs procedural operations.
JNK's solution may give you what you're looking for in this instance, but I would question what exactly you would need that type of solution for in the first place.
您可以使用游标来迭代查询返回的所有数据。
You could use a cursor to iterate over all of the data returned from your query.