使用游标,查询一张的数据往另外三张表里面添加数据

测试表结构如图

-- 方法1:游标
-- 声明变量
DECLARE
    @Name nvarchar(50),
    @Sex bit,
    @Age int;
    
    
set @Age=1;

-- 声明游标
DECLARE C_Employees CURSOR FAST_FORWARD FOR
    SELECT  Name, Sex FROM Test
    
OPEN C_Employees;

-- 取第一条记录
FETCH NEXT FROM C_Employees INTO @Name,@Sex;

WHILE @@FETCH_STATUS=0
BEGIN

    -- 操作
    insert into dbo.TestName values(@Name)
    insert into dbo.TestSex values(@Sex)
    insert into dbo.TestAge values(@Age)
    
    set @Age+=1;
    -- 取下一条记录
    FETCH NEXT FROM C_Employees INTO @Name,@Sex;
    
END
-- 关闭游标
CLOSE C_Employees;
-- 释放游标
DEALLOCATE C_Employees;
posted @ 2019-12-13 11:26  Smile灬Lucky  阅读(297)  评论(0编辑  收藏  举报