ASPForums.Net RSS Feed additions to the content that appears on ASPForums.Net(c) 2019 All rights reserved.Compare and Insert SUM value with Another Table using CURSOR in SQL Server<p>Hey</p> <p><span style="text-decoration: underline;"><strong>SQL</strong></span></p> <pre class="brush: sql">DECLARE @Table1 AS TABLE(ID INT, Total INT) DECLARE @Table2 AS TABLE(ID INT) DECLARE @Total_In AS TABLE (totalid INT, totalsum INT) INSERT INTO @Table1 VALUES(1,100) INSERT INTO @Table1 VALUES(2,400) INSERT INTO @Table1 VALUES(3,300) INSERT INTO @Table1 VALUES(4,200) INSERT INTO @Table1 VALUES(4,200) INSERT INTO @Table2 VALUES(1) INSERT INTO @Table2 VALUES(3) INSERT INTO @Table2 VALUES(2) INSERT INTO @Table2 VALUES(4) DECLARE @totalid INT DECLARE @totalsum INT DECLARE @id INT SET @id = 4 DECLARE #R CURSOR FOR SELECT SUM(T2.ID) ID, Sum(Total) FROM @Table1 T1 INNER JOIN @Table2 T2 ON T2.Id=T1.Id WHERE T2.Id = @id OPEN #R -- FETCH NEXT FROM #R INTO @totalid,@totalsum -- check for a new row WHILE @@FETCH_STATUS=0 BEGIN INSERT INTO @Total_In SELECT @totalid,@totalsum FETCH NEXT FROM #R INTO @totalid,@totalsum END CLOSE #R DEALLOCATE #R SELECT * FROM @Total_In</pre> <p><span style="text-decoration: underline;"><strong>Output</strong></span></p> <table border="1"> <tbody> <tr> <td>totalid</td> <td>totalsum</td> </tr> <tr> <td>8</td> <td>400</td> </tr> </tbody> </table>, 27 Nov 2018 03:45:17 GMT