Friday, September 15, 2017

SQL Server loop through all records or loop through a set of records without cursor in Stored Proceure/function.



              SELECT * INTO #TEMPRES
              FROM
              (
                     SELECT ROW_NUMBER() OVER(order by (SELECT 1)) AS SerialNo, RES.Column1, RES.Column2
                     FROM (SELECT DISTINCT Column1, Column2
                           FROM teble1 WHERE Column2= 'test' ) AS RES
              ) AS X


              --SELECT * FROM #TEMPRES
              --//// MAKING LOOP OF RECORDS ////
              DECLARE @RowCnt INT = 1
              SELECT @RowCnt=COUNT(*) FROM #TEMPRES
              IF(@RowCnt > 0)
              BEGIN
                     DECLARE @i INT = 1
                     WHILE(@i <= @RowCnt)
                     BEGIN
                                  SELECT ProjectLPDetailsBatchID FROM #TEMPRES WHERE SerialNo = @i    
                           END
                           SET @i = @i + 1
                     END
              END

              DROP TABLE #TEMPRES

No comments:

Post a Comment