2017-04-04 110 views
0
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 

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

+1

谷歌 – FLICKER

+0

我试过,但找不到任何的理解或简单的,实际上插入到表中的一些“在SQL Server使用游标示例”。 – Sandy777

+0

为什么即使打扰**游标**?那些是邪恶的,浪费你的CPU周期 - 只要你可以避免它们! (和大多数时候,**你可以!**) –

回答

1

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

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

谢谢。但你能否让我知道,如果我可以硬编码两列并插入数据,因为它是其他列?当然是 – Sandy777

+0

。在那种情况下,你只需要一个变量 – FLICKER

+0

是否应该创建我想要插入的所有列的变量? – Sandy777