Reputation: 849
I want to use cursor to delete record from table. How can I do it?
I use MSSQL 2008 Express this code does not delete anything from #temp. I also tried where current of cursor_name did not work.
Here is my sample code:
use AdventureWorks
drop table #temp
select * into #temp from HumanResources.Employee;
declare @eid as int;
declare @nid as varchar(15);
DECLARE Employee_Cursor CURSOR FOR
SELECT A.EmployeeID, A.NationalIDNumber FROM #temp AS A
OPEN Employee_Cursor;
FETCH NEXT FROM Employee_Cursor INTO @eid , @nid ;
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@eid > 10)
BEGIN
delete from #temp where #temp.EmployeeID = @eid;
END
FETCH NEXT FROM Employee_Cursor;
END;
CLOSE Employee_Cursor;
DEALLOCATE Employee_Cursor;
GO
select * from #temp
thanks in advance
Upvotes: 7
Views: 45369
Reputation: 1666
There is a much simpler answer - use this command:
delete from HumanResources.Employee where current of Employee_Cursor
It's called 'Positioned delete' and described at MSDN.
Upvotes: 6
Reputation: 849
use AdventureWorks
select * into #temp from HumanResources.Employee;
declare @eid as int;
declare @nid as varchar(15);
DECLARE Employee_Cursor CURSOR FOR
SELECT A.EmployeeID, A.NationalIDNumber FROM #temp AS A
OPEN Employee_Cursor;
FETCH NEXT FROM Employee_Cursor INTO @eid , @nid ;
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@eid > 10)
BEGIN
delete from #temp where current of Employee_Cursor
END
FETCH NEXT FROM Employee_Cursor INTO @eid , @nid ;
END;
CLOSE Employee_Cursor;
DEALLOCATE Employee_Cursor;
select * from #temp
drop table #temp
this works for me
Upvotes: 7
Reputation: 4469
Could you please try in below ways, thanks for your time.
You have fetched data from cursor but didn't push into your variables missed in WHILE
loop, please have a look on below code, thanks.
drop table #temp
select * into #temp from Employee;
declare @eid as int;
declare @nid as varchar(15);
DECLARE Employee_Cursor CURSOR FOR
SELECT A.EmployeeID, A.NationalIDNumber FROM #temp AS A
OPEN Employee_Cursor;
FETCH NEXT FROM Employee_Cursor INTO @eid , @nid ;
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@eid > 10)
BEGIN
delete from #temp where #temp.EmployeeID = @eid;
END
FETCH NEXT FROM Employee_Cursor INTO @eid , @nid ;
END;
CLOSE Employee_Cursor;
DEALLOCATE Employee_Cursor;
GO
select * from #temp
Update:
I've changes in 2nd FETCH
statement, just have added below highlighted part, thanks
FETCH NEXT FROM Employee_Cursor INTO @eid , @nid ;
Upvotes: 0