如何检查Cursor Select查询是否有记录

时间:2017-08-23 09:31:30

标签: sql-server tsql stored-procedures cursor

我是Stored Procedures的新手。我想有一个光标用于从表中选择记录。如果记录可用,请插入另一个。如何在insert.Thanks提前添加对所选行的检查。

例如:

DECLARE cursor_name CURSOR FOR 
        SELECT Id From tbl WHERE  where condition
OPEN cursor_name 

    FETCH NEXT FROM cursor_name INTO @id
    WHILE @@FETCH_STATUS = 0   
    BEGIN  
     Insert statement

1 个答案:

答案 0 :(得分:0)

变量@@ FETCH_STATUS仅在成功选择行时返回0,具体取决于您的where条件。您在问题中提供的代码足以照顾它。您也可以参考下面的示例代码。在这段代码中,如果column1的值是偶数并丢弃奇数行,我将从table1插入到table2的行 -

-- 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