2012-01-11 54 views
4

我想用光標從表中刪除記錄。我該怎麼做?如何使用光標刪除表中的記錄

我使用MSSQL 2008 Express此代碼不會從#temp中刪除任何內容。我也嘗試了當前的cursor_name沒有工作。

這裏是我的示例代碼:

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 

在此先感謝

+2

對於所有神聖的愛,爲什麼你用光標來代替簡單的刪除查詢呢?你對DBA有怨恨嗎? – JohnFx 2012-01-11 04:10:15

+0

愚蠢的問題,但你有僱員表中的任何EmployeeID> 10?另外你爲什麼要爲此做一個光標?這是一個非常低效的方法。 還要確保沒有觸發器正在中止刪除。 – Jordan 2012-01-11 04:12:20

+0

@JohnFx不,我只是好奇地做,只是爲了學習,在實踐中我也使用簡單的刪除語句 – vivek 2012-01-11 04:13:18

回答

2
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 

這對我的作品

0

請您嘗試以下方法,感謝您的時間。

您已經從光標提取數據,但沒有將您的變量推入WHILE循環中錯過,請看下面的代碼,謝謝。

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 

更新: 我在第二FETCH聲明的變化,只是增加了下面突出的部分,由於

NEXT來去Employee_Cursor INTO @eid,@nid;

+0

它與我的不同嗎? ,好吧,我嘗試過,但沒有工作,無論如何感謝您的興趣 – vivek 2012-01-11 05:01:35

+0

對不起,對於最近的回覆,但是,我要改變我的答案,請看看它,謝謝 – 2012-01-11 06:57:14

+0

當代碼看起來如此類似於原,它通常對於突出顯示已經改變的內容非常有幫助(我假設它將'INTO'添加到第二個'FETCH'中,因爲這就是我正要回答的問題) – 2012-01-11 07:42:44

1

還有一個更簡單的答案 - 使用這個命令:

delete from HumanResources.Employee where current of Employee_Cursor 

這就是所謂的 '定位刪除',並在MSDN描述。