如何使用Cursor在现有表中插入记录

时间:2017-04-04 23:55:06

标签: sql sql-server cursor

 Declare Userrole_Cursor Cursor For
 Select (User_Role_id,
     Pos_entity_Id,
     User_role_code,
     User_Role_description,
     Print_Sequence,
     Update_date,
     Tx_id,
     Add_date,
     Add_Username,
     Update_Username,
     Active_Flag) from User_Role_Tb where pos_entity_id = (pos_entity_id)

     Open Cursor 

  FETCH NEXT FROM UserRole_Cursor into 

以上是我编写的Cursor创建,现在需要在User_role_tb中的所有提到的列中插入。请帮忙。这是我第一次使用光标。

1 个答案:

答案 0 :(得分:0)

这个简单的例子可以帮助你

-- assume this is your table
create table #tmp (MyDbName varchar(100), MyDbId int, MyStatus int)

-- you need to have a variable for each field. 
DECLARE @MyDbName varchar(100)
DECLARE @MyDbId int
DECLARE @MyDbStatus int

DECLARE db_cursor CURSOR FOR  
    SELECT name, [dbid], [status]
    FROM master.dbo.sysdatabases 

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @MyDbName, @MyDbId, @MyDbStatus    

WHILE @@FETCH_STATUS = 0   
BEGIN   
    -- insert data into your table using variables
    insert into #tmp (MyDbName, MyDbId, MyStatus)
    values (@MyDbName, @MyDbId, @MyDbStatus)

    -- fetch next row from cursor
    FETCH NEXT FROM db_cursor INTO @MyDbName, @MyDbId, @MyDbStatus    
END   

CLOSE db_cursor   
DEALLOCATE db_cursor

-- select from your table to make sure data is there
select * from #tmp