游标

Posted on 2011-01-15 12:13 moss_tan_jun 阅读(98) 评论(0) 编辑 收藏
创建游标分五个步骤:

 

-- =============================================
-- Author:      Zehui Shu
-- Create date: 2010-12-23
-- Description: 通过游标实现同步表数据
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Syn_Data]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @ID INT;
    TRUNCATE TABLE Table2;

 

    -- 1.声明游标
    DECLARE CUR_MonthID CURSOR FOR
    SELECT ID FROM [Table1]
    
    -- 2.打开游标
    OPEN CUR_MonthID
    -- 3.从一个游标中查找信息,实现自己的数据处理。
    FETCH CUR_MonthID INTO @ID
    WHILE @@FETCH_STATUS=0
    BEGIN
        INSERT INTO [Table2]
        SELECT * FROM [Table1] tm WHERE tm.ID=@ID
        FETCH NEXT FROM CUR_MonthID INTO @ID
    END;

    -- 4.关闭游标
    CLOSE CUR_MonthID;
    
    -- 5.释放游标
    DEALLOCATE CUR_MonthID;
END