我在SPROC中插入语句(简化),如下所示
SET ROWCOUNT 100
WHILE(1=1)
BEGIN
INSERT INTO table1
SELECT *
FROM table2
WHERE some_condition
-- EDIT: Realized forgot to include this following vital line that is causing issue
SET @var = @var + @@ROWCOUNT
-- @@ROWCOUNT now takes on a value of 1, which will cause the following IF check to fail even when no lines are inserted
IF(@@ROWCOUNT = 0)
BEGIN
BREAK
END
END
但问题是,在任何操作后,即使我的some_condition
没有更多行,@@ROWCOUNT
也等于1
,而不是0
。
如果返回的0行与我的some_condition
匹配,我怎么能打破这个循环?
答案 0 :(得分:7)
“set”语句创建的行数为1.您应该立即将@@ ROWCOUNT保存到@rowCount变量中并稍后使用该变量。
declare @rowCount int
WHILE(1=1)
BEGIN
INSERT INTO table1
SELECT *
FROM table2
WHERE some_condition
-- EDIT: Realized forgot to include this following vital line that is causing issue
SET @rowCount = @@ROWCOUNT
SET @var = @var + @rowCount
-- @@ROWCOUNT now takes on a value of 1, which will cause the following IF check to fail even when no lines are inserted
IF(@rowCount = 0)
BEGIN
BREAK
END
END
此外,您可以通过将@rowCount初始设置为-1并将WHILE条件更改为@rowCount<>来简化操作。 0.将不再需要有条件的BREAK。
答案 1 :(得分:0)
另一种解决方案。这将检查每次迭代以查看最后插入的记录的ID是否已更改。如果它没有改变,则表示没有添加该迭代的记录。
SET ROWCOUNT 100
declare @id int;
WHILE(1=1)
INSERT INTO table1
SELECT *
FROM table2
WHERE some_condition
IF(@id= @@identity)
BEGIN
BREAK
END
set @id = @@identity;
END
答案 2 :(得分:0)
尝试此解决方案:
第一个解决方案
在循环条件中使用@@ROWCOUNT
。
SET ROWCOUNT 100
INSERT INTO table1
SELECT *
FROM table2
WHERE some_condition
WHILE(@@ROWCOUNT > 0)
BEGIN
INSERT INTO table1
SELECT *
FROM table2
WHERE some_condition
END
第二次解决
使用goto
。
SET ROWCOUNT 100
WHILE(1=1)
BEGIN
INSERT INTO table1
SELECT *
FROM table2
WHERE some_condition
IF(@@ROWCOUNT = 0)
BEGIN
goto label
END
END
label1:
print 'After lopp'
答案 3 :(得分:0)
我认为您应该使用select
将@@rowcount
变为变量。试试这个:
declare @number_of_rows int
SET ROWCOUNT 100
WHILE(1=1)
BEGIN
INSERT INTO table1
SELECT *
FROM table2
WHERE some_condition
SELECT @number_of_rows=@@ROWCOUNT
IF (@number_of_rows = 0)
BEGIN
BREAK
END
END
答案 4 :(得分:-6)
实施类似于Moho的解决方案,但使用SELECT
代替SET
来存储@@ROWCOUNT
。