カーソルを使用してデータベースにデータを挿入するクエリがあります。奇妙なことに、クエリは 1 回目に実行されますが ( SSMS > Execute )、2 回目に実行すると、カーソルのある部分が実行されません。
ただし、「デバッグ」をクリックすると、デバッグでき、クエリ全体が正常に実行されます。その直後、もう一度問題なく動作し、最初の挿入スクリプトだけが実行されます。
ここで述べたように FAST_FORWARD を試しましたが、問題は解決していないようです。助言がありますか?
/** 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
2回目、これだけ:
(1 row(s) affected)
実際、カーソル内の挿入は実行されませんでした。