Compare and Insert SUM value with Another Table using CURSOR in SQL Server

Last Reply one year ago By pandeyism

Posted one year ago

I have a stored procedure that works fine but I need to add more functions inside it and I do not know how to do it. I need to compare the sum of the accounts by id with the total of another table with the same account id and insert values in a table

SUM VALUES FROM TABLE 1 

Select ID , SUM(Total) AS Sum FROM TABLE1 GROUP BY ID

Record every register n Compare  with table2 

SELECT ID  FROM TABLE2  WHERE ID  = @id

and insert table VALIDATE 

INSERT INTO VALIDATE (ID,TOTALTAble1 , TOTALTABLE2 ) VALUES (@id , @sum , @totaltable2)

 stored procedure

DECLARE #R
CURSOR FOR
SELECT  ID, Sum(b) 
      FROM Ing
	  WHERE a = 2014
	  GROUP BY ID
OPEN #R
-- 
FETCH NEXT FROM #R INTO 
@id,@total, @name
 
-- check for a new row
WHILE @@FETCH_STATUS=0
BEGIN

INSERT INTO dbo.Total_In
SELECT @id,@totakl, @name

FETCH NEXT FROM #R INTO @id,@total, @name  
END
CLOSE #R
DEALLOCATE #R

Regards

This question does not have replies that have been liked.