2012-10-18 73 views
0

我有一個使用遊標將數據插入到我的數據庫的查詢。奇怪的是查詢第一次運行(SSMS> Execute),但是如果我第二次運行它,帶有遊標的部分不會執行。TSQL光標的結果不一致

但是 - 如果我然後打'調試'我可以調試和整個查詢執行得很好。在此之後,它再次正常工作,然後再次只執行第一個插入腳本。

我試過FAST_FORWARD,提到here但這似乎並不能解決問題。有什麼建議麼?

/** Declarations **************************************************/ 
DECLARE @TemplateFileName varchar(200) 
DECLARE @TemplatePreviewFileName varchar(200) 
DECLARE @TemplateId int 
DECLARE @CompanyId int 
DECLARE CompanyCursor cursor FAST_FORWARD FOR SELECT [CmpId] from SetCompany 
/******************************************************************/ 

/** Set template name here ****************************************/ 
SET @TemplateFileName   = 'Template_2' 
SET @TemplatePreviewFileName = 'Template_2' 
/******************************************************************/ 

/******************************************************************/ 
INSERT INTO ... etc 
SET @TemplateId = @@IDENTITY; 
Open CompanyCursor 

WHILE @@FETCH_STATUS = 0 
    BEGIN  
     IF(@CompanyId IS NOT NULL) 
     BEGIN 
      PRINT 'Adding template ' + @TemplateFileName + ' with id ' + convert(varchar, @TemplateId) + ' to company ' + convert(varchar, @CompanyId); 
      INSERT INTO .... etc 
      PRINT 'OK'; 
     END 
     Fetch NEXT FROM CompanyCursor INTO @CompanyId 
END 
CLOSE CompanyCursor; 
DEALLOCATE CompanyCursor; 

運行 '第一' 的時候,我得到:

(1 row(s) affected) 
Adding template Template_2.frx with id 2272 to company 10 

(1 row(s) affected) 
OK 
Adding template Template_2.frx with id 2272 to company 11 

(1 row(s) affected) 
OK 
Adding template Template_2.frx with id 2272 to company 12 

(1 row(s) affected) 
OK 
Adding template Template_2.frx with id 2272 to company 13 

(1 row(s) affected) 
OK 
Adding template Template_2.frx with id 2272 to company 14 

(1 row(s) affected) 
OK 

第二次,只有這個:

(1 row(s) affected) 

事實上,光標內插入未運行。

+0

更好的解決方案:完全避免雜亂的那個光標! :-) –

+0

@marc_s - 你如何建議我這樣做? –

+0

只是一個'INSERT INTO ..... SELECT ..... FROM .....' - 根本不需要光標 –

回答

3

Open CompanyCursor 

添加

FETCH NEXT FROM CompanyCursor 
INTO @CompanyId 
+0

謝謝!這解決了它。但爲什麼它第一次運行? –