Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I want to use cursor after with keyword its giving an error incorrect syntax near...

What I have tried:

SQL
BEGIN TRANSACTION
		;WITH C AS
		(
		  SELECT MC_id
		  FROM CM_MaterialCategory
		  WHERE MC_id IN (SELECT id FROM @id)
		  UNION ALL
		  SELECT T.MC_id
		  FROM CM_MaterialCategory AS T INNER JOIN C ON T.MC_parent = C.MC_id
		)
		DECLARE A CURSOR FOR SELECT DISTINCT MC_id FROM C
			UPDATE CM_MaterialCategory SET MC_isdeleted=1 WHERE MC_id IN(29,28,27)
			 
			UPDATE CT_MaterialCategory SET TMC_isdeleted=1 WHERE TMC_id=@TMCID

			EXEC Insertinto_Log @tablename='CM_MaterialCategory',@fun=2,@U_id=@U_id,@Key=@MC_id,@datetime=@ErrorTime
			EXEC Insertinto_Log @tablename='CT_MaterialCategory',@fun=2,@U_id=@U_id,@Key=@TMCID,@datetime=@ErrorTime
		COMMIT
Posted
Updated 5-May-16 4:18am
v2
Comments
Dave Kreskowiak 5-May-16 10:44am    
As Chill60 has said already, you REALLY need to try and avoid using a CURSOR whenever possible. Cursors do not scale well as they will run slower and slower the greater the number of records you have the Cursor iterating over.
itsmehaboob 6-May-16 0:52am    
Yeah that's really we are doing now(removing all cursors) but in this case i want to run a sub query before updating CM_table for getting CT_tables's primary key then only possible to update CT_Table(Second Update query in that section) can you give any suggestion for that ?

1 solution

Declare the cursor before the CTE i.e.
SQL
DECLARE A CURSOR FOR
WITH C AS
(
  SELECT MC_id
  FROM CM_MaterialCategory
  WHERE MC_id IN (SELECT id FROM @id)
  UNION ALL
  SELECT T.MC_id
  FROM CM_MaterialCategory AS T INNER JOIN C ON T.MC_parent = C.MC_id
)
SELECT DISTINCT MC_id FROM C

This solution comes with all the usual warnings about cursors - are you sure you can't do this with set-based processing?

And I don't think your code is going to work without a FETCH somewhere
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900