I’ve got a query that uses a cursor to insert data into my database. The weird thing is that the query runs the 1st time ( SSMS > Execute ), but if I run it a second time, the part with the cursor does not execute.
However – If i then hit ‘debug’ I can debug and the whole query executes just fine. Right after that it works just fine once more and then, again, only the first insert script executes.
I tried the FAST_FORWARD as mentioned here but that doesn’t seem to solve the problem. Any suggestions?
/** 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;
Running the ‘first’ time, I get:
(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
Second time, only this:
(1 row(s) affected)
And indeed, the insert inside the cursor did not run.
After
Add