变量@@ FETCH_STATUS只会在成功行的情况下返回0,则选择您的WHERE条件。您在问题中提供的代码将足以处理它。你也可以参考下面的示例代码。在这段代码中我从表1插入行表2列1如果的值为偶数和丢弃奇数行 -
-- CREATE Source table and add few records
create table #Table1
(
Col1 int,
col2 char(1)
)
insert into #Table1
select 1, 'A'
union all select 2, 'B'
union all select 3, 'C'
union all select 4, 'D'
union all select 5, 'E'
union all select 6, 'F'
union all select 7, 'G'
union all select 8, 'H'
--Create destination table
create table #Table2
(
Col1 int,
col2 char(1)
)
declare @Col1 int, @col2 char(1)
-- below cursor will insert only evern rows from surce table to destination
table
DECLARE Cur1 CURSOR FOR
SELECT Col1, col2
FROM #Table1
WHERE col1%2 = 0
OPEN Cur1
FETCH NEXT FROM Cur1 INTO @Col1 ,@col2
WHILE @@FETCH_STATUS = 0 -- this will return 0 only if a successful row is fatched
BEGIN
insert into #Table2
select @Col1 ,@col2
FETCH NEXT FROM Cur1 INTO @Col1 ,@col2
END
CLOSE Cur1
DEALLOCATE Cur1
这个检查就足够了'WHILE @@ FETCH_STATUS = 0' – TheGameiswar
你确定要使用一个光标?如果您将记录从一张表插入另一张表中,则不需要执行此操作,并且性能会很差。你可能会更好地使用条件INSERT语句。看到这里:https://www.w3schools.com/sql/sql_insert_into_select.asp关心, – Barnsite