Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How i can use cursor to delete record from table

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

like image 488
vivek Avatar asked Jan 11 '12 04:01

vivek


People also ask

How do you delete cursor records?

To delete a record using a cursor, simply position the cursor to the record that you want to delete and then call Cursor. delete() .

How can we delete records in a table?

DELETE SyntaxDELETE FROM table_name WHERE condition; Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted.

Which command is used to delete the record from a table?

The DELETE command is used to delete existing records in a table.

What is cursor delete?

Cursor Delete. The cursor version deletes the row to which the specified cursor is pointing. If the cursor is not currently pointing at a row when the delete is executed, the DBMS Server generates an error. To position the cursor to a row, issue a FETCH statement.


2 Answers

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

like image 117
vivek Avatar answered Sep 25 '22 02:09

vivek


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.

like image 28
vlad2135 Avatar answered Sep 22 '22 02:09

vlad2135