sql - 为什么 SQL Continue 语句会创建一个 Endless 循环而不是 Continuing?
问题描述
试图在一个简单的循环中使用 CONTINUE 语句。
该循环在没有 IF=16 和 CONTINUE 语句的情况下工作,但不适用于它们
DECLARE @counter INT
DECLARE @maxLocations INT
DECLARE @numLocations INT
SET @maxLocations = (SELECT MAX(calculated_host_listings_count) FROM [PracticeDB].[dbo].[AB_NYC_2019$])
SET @counter = 0
WHILE @counter<=@maxLocations
BEGIN
SET @numLocations =
(SELECT COUNT(*) FROM [PracticeDB].[dbo].[AB_NYC_2019$] WHERE calculated_host_listings_count = @counter)
IF(@numLocations=16)
BEGIN
CONTINUE
END
ELSE
BEGIN
PRINT CAST(@numLocations AS VARCHAR(6)) + ' rentals with ' +
CAST(@counter as VARCHAR(6)) + ' host listings'
END
SET @counter += 1
END
结果没有IF(@numlocations=16) 继续
0 rentals with 0 host listings
32303 rentals with 1 host listings
6658 rentals with 2 host listings
2853 rentals with 3 host listings
1440 rentals with 4 host listings
845 rentals with 5 host listings
570 rentals with 6 host listings
399 rentals with 7 host listings
416 rentals with 8 host listings
234 rentals with 9 host listings
210 rentals with 10 host listings
110 rentals with 11 host listings
180 rentals with 12 host listings
130 rentals with 13 host listings
70 rentals with 14 host listings
75 rentals with 15 host listings
16 rentals with 16 host listings
68 rentals with 17 host listings
IF & Continue 的结果(上面的原始代码)进入一个无限循环,但是当我停止时,我得到结果直到 IF 结果之前(16)
0 rentals with 0 host listings
32303 rentals with 1 host listings
6658 rentals with 2 host listings
2853 rentals with 3 host listings
1440 rentals with 4 host listings
845 rentals with 5 host listings
570 rentals with 6 host listings
399 rentals with 7 host listings
416 rentals with 8 host listings
234 rentals with 9 host listings
210 rentals with 10 host listings
110 rentals with 11 host listings
180 rentals with 12 host listings
130 rentals with 13 host listings
70 rentals with 14 host listings
75 rentals with 15 host listings
解决方案
在 SQL WHILE 循环中使用 CONTINUE 语句,以便在某些条件发生时停止循环的当前迭代,然后从循环的开头开始新的迭代 SQL WHILE 循环与简单示例
根据您的问题,您需要在 CONTINUE 语句之后或之前迭代计数器变量。恕我直言,您的查询将是这样的;
DECLARE @counter INT
DECLARE @maxLocations INT
DECLARE @numLocations INT
SET @maxLocations = (SELECT MAX(calculated_host_listings_count) FROM [PracticeDB].[dbo].[AB_NYC_2019$])
SET @counter = 0
WHILE @counter<=@maxLocations
BEGIN
SET @numLocations =
(SELECT COUNT(*) FROM [PracticeDB].[dbo].[AB_NYC_2019$] WHERE calculated_host_listings_count = @counter)
IF(@numLocations=16)
BEGIN
SET @counter += 1 --Changed part
CONTINUE
END
ELSE
BEGIN
PRINT CAST(@numLocations AS VARCHAR(6)) + ' rentals with ' +
CAST(@counter as VARCHAR(6)) + ' host listings'
END
SET @counter += 1
END
推荐阅读
- hbase - 问题 - 恢复 HBase 映像
- sql - 如何指定我试图选择的值只是时间?
- sql - Oracle json_object 选择奇怪的 unicode 符号而不是文本
- python - 如何让 pip 在 setup.cfg extras 中使用 git url 作为包源?
- c# - 如何保存/读取列表
在 XML 中? - java - Java如何避免将类作为泛型对象的参数传递
- coq - 定义无限树的等式关系
- firebase - 经过身份验证的用户的 Firebase 存储规则不起作用
- html - 如何通过单击列表项将 json 对象属性发送回 NODE?
- scala - 如何在 sbt shell 会话开始时显示项目特定的消息?