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
To delete a record using a cursor, simply position the cursor to the record that you want to delete and then call Cursor. delete() .
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.
The DELETE command is used to delete existing records in a table.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With